gpt4 book ai didi

asp.net - Microsoft.EntityFrameworkCore.dll 中出现类型为 'Microsoft.EntityFrameworkCore.DbUpdateException' 的异常

转载 作者:行者123 更新时间:2023-12-04 12:50:54 25 4
gpt4 key购买 nike

我很长一段时间都遇到麻烦。让我们想象一下这个例子:

public class Coordinate {

public int id {get;set;}
public int x {get;set;}
public int y {get;set;}
}
public class Planet {

public int id {get;set;}
public string name {get;set;}
public Coordinate coordinate {get;set;}
}

我创建了两个模型,模型 Planet 具有模型坐标作为属性。现在想象一下,我在代码的某处创建了一个坐标并将其存储在数据库中。想象一下这是坐标:

Coordinate c = new Coordinate();
c.x = 1;
c.y = 2;

然后我将它添加到我的数据库并保存。

但是当我创建一个行星时,我会:

planet.coordinate = c;

然后我尝试将它添加到数据库中,但出现以下错误:

An exception of type 'Microsoft.EntityFrameworkCore.DbUpdateException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

Additional information: An error occurred while updating the entries. See the inner exception for details.

我知道我可以将属性 public Coordinate coordinate 更改为 public int coordinate_id 但我想改为使用 Coordinate 模型来执行此操作。

我正在使用 ASP NET CORE 1.0

杯子

最佳答案

你的问题是此时c已经有了一个Id。

使用 planet.Add,行星和所有附加到它的坐标将在您的 DbSet 中设置为 Added,并且在调用 SaveChanges 时,将创建插入语句。 (这里我假设你的列和你的 Id 属性自动递增)

当SaveChanges完成后,EF会看到行星在数据库中,但是刚刚添加的坐标的Id不同(它被DBMS改变了,所以现在坐标在你的数据库中有两次,有两个不同的Id ), 所以它会预料到出了点问题并抛出这个异常。

当你没有重复条目的问题时,将 Id 设置为 null 或 0。否则,有两种解决方案:

-只设置FK属性,不设置导航属性

-仅调用 SaveChanges 一次(例如,只添加行星,但是添加坐标关系修正应该导致相同的结果)

关于asp.net - Microsoft.EntityFrameworkCore.dll 中出现类型为 'Microsoft.EntityFrameworkCore.DbUpdateException' 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38751816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com