当在同一对象上应用两次时,EntityState.Unchanged会崩溃

时间:2018-02-02 08:35:46

标签: c# entity-framework

我正在尝试保存类型为ChangeRequest的对象,该对象具有多个导航属性。对于这些属性,我已将其EntityState设置为Unchanged以防止Entity Framework在我的数据库中创建重复项。 对于大多数这些属性,它们的状态会成功更改,并且不会持久保存到数据库中。

当我执行以下操作时:db.Entry(changeRequest_Database_Server.Database_Server.Server).State = EntityState.Unchanged;用于Server对象 然后再说一遍:

db.Entry(changeRequest_Server_Application.Server_Application.Server).State = EntityState.Unchanged; 对于同一服务器对象,我得到例外:

  

Saving or accepting changes failed because more than one entity of type 'ChangeControl.Business.Server' have the same primary key value. Ensure that explicitly set primary key values are unique...

这是我的代码:

db.ChangeRequests.Add(changeRequest);

db.Entry(changeRequest.BusinessUnit).State = EntityState.Unchanged;

foreach (var changeRequest_ChangeType in changeRequest.ChangeRequest_ChangeType)
{
    db.Entry(changeRequest_ChangeType.ChangeType).State = EntityState.Unchanged;
}
foreach (var changeRequest_Attachment in changeRequest.ChangeRequest_Attachment)
{
    db.Entry(changeRequest_Attachment.Attachment).State = EntityState.Unchanged;
}
foreach (var changeRequest_Attachment in changeRequest.ChangeRequest_Attachment)
{
    db.Entry(changeRequest_Attachment.Attachment).State = EntityState.Unchanged;
}
foreach (var changeRequest_Database_Server in changeRequest.ChangeRequest_Database_Server)
{
    db.Entry(changeRequest_Database_Server.Database_Server).State = EntityState.Unchanged;
    db.Entry(changeRequest_Database_Server.Database_Server.Server).State = EntityState.Unchanged;
    db.Entry(changeRequest_Database_Server.Database_Server.Database).State = EntityState.Unchanged;
}
foreach (var changeRequest_Requirement in changeRequest.ChangeRequest_Requirement)
{
    db.Entry(changeRequest_Requirement.Requirement).State = EntityState.Unchanged;
}
foreach (var changeRequest_Server_Application in changeRequest.ChangeRequest_Server_Application)
{
    db.Entry(changeRequest_Server_Application.Server_Application).State = EntityState.Unchanged;
    db.Entry(changeRequest_Server_Application.Server_Application.Server).State = EntityState.Unchanged;
    db.Entry(changeRequest_Server_Application.Server_Application.Application).State = EntityState.Unchanged;
}

db.SaveChanges();

我已尝试thisthis无济于事。

如何检查未跟踪的对象并确保没有在我的数据库中插入重复项?

0 个答案:

没有答案