0

我只是在构建一个模型,然后尝试通过该.SaveChanges()函数将其插入数据库,但是当我运行时,SaveChanges() 我得到一个数据库错误,表明发生了主键重复......

所以我深入研究了 SQL 日志记录,发现这个模型插入试图重新插入已经存在的数据......为什么会发生这种情况?

我的代码

using (var dbContext = new dbContext(_dbContextOptions))
{
    Request request = new Request()
    {
       RequesterId = 1,
       HelpRequestType = helpRequestTypeObject, //new model is being inserted for this on .SaveChanges()
       Status = statusObject, //new model is being inserted for this on .SaveChanges()
       AssignmentKeyId = 12, 
       TimeCreated = DateTime.Now,
       CustomContactIds = null
    };

    //add request to transaction
    dbContext.Request.Add(request);
    dbContext.SaveChanges();
}

编辑:所以我改变了一切来创建模型,只使用外键引用的id(没有直接链接的实体),这似乎解决了我的问题。一旦创建了实体并应用了 .SaveChanges() ,模型就会像预期的那样链接到所有其他实体。似乎我使用以前在不同 DbContext 下查询过的实体而不是我用于创建这个新实体的活动实体给自己造成了问题。

4

2 回答 2

1

但似乎问题在于我直接将现有实体模型链接到新模型,而不是通过 ID 链接它们......

我正在从数据库中查询现有实体并将它们直接链接到这个新的请求对象,而不仅仅是通过 ID...这导致实体框架试图重新制作所有现有实体...

当您使用多个实体时DbContext,您需要小心。如果您HelpRequestType从 查询一个对象contextA,并将其连接到属于 的一个对象contextB,则contextB没有跟踪该HelpRequestType对象并且无法知道该对象已经是底层数据库的一部分。因此,它认为该对象是新的。如果两个上下文都属于相同的派生类型,这甚至是正确的。

如果DbContext出于某种原因需要使用两个不同的对象,则需要先Attach() to的HelpRequestType对象,然后再调用.contextAcontextBSaveChanges()contextB

DbContext通常,对于所有操作(工作单元模式)只使用单个对象会更容易。您应该有充分的理由(性能、在多个数据存储上分区的模型等)使用多个DbContext.

有关更多详细信息,另请参阅在 Entity Framework Core中使用断开连接的实体图。

于 2020-02-28T11:11:48.580 回答
0

So I'm not exactly sure why it was the issue, as I thought I had seen this done elsewhere... But it appears the issue was that I was directly linking existing entity models to the new model instead of linking them by ID...

I was querying for existing entities from the database and linking them to this new Request object directly rather than just by ID... This resulted in Entity Framework attempting to remake all the existing entities...

I changed the places I was using models instead of IDs and it all appears to be working now.

于 2020-02-25T17:23:11.173 回答