将实体修改为EF中的上下文



我有一个实体,其中包含另一个实体的列表。

 public virtual List<PeopleAddress> Addresses{ get; set; }

在编辑此实体时,用户可以将新地址添加到AddressList。

邮寄方式:

 _db.Entry(people).State = EntityState.Modified;
 _db.SaveChanges();

那个people.Addresses有4条记录。2条记录保存在PeopleAddress中,但添加了两条Id为0的新记录。

EntityState.Modified中获取错误:

Attaching an entity of type 'Web.Models.PeopleAddress' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

我的问题是:

EF不能添加记录?在编辑人员之前,我应该手动添加新记录吗?

异常消息已经告诉您要做什么:

这可能是因为一些实体是新的,并且尚未接收到数据库生成的键值在这种情况下,请使用"Add"方法或"Added"实体状态来跟踪图形,然后根据需要将非新实体的状态设置为"Unchanged"或"Modified">

换句话说,当您调用SaveChanges时,您需要确保每个新的PeopleAddress的状态都是Added,而不是Modified。像这样的东西应该工作

_db.People.Add(people);
_db.Entry(people).State = EntityState.Modified;
foreach(PeopleAddress address in newAdddresses) {
    _db.Entry(address).State = EntityState.Unchanged;
}

最新更新