我有一个包含另一个实体列表的实体。
public virtual List<PeopleAddress> Addresses{ get; set; }
在编辑此实体时,用户可以向AddressList添加新地址。
在post方法中:
_db.Entry(people).State = EntityState.Modified;
_db.SaveChanges();
people.Addresses
有4条记录。 2记录保存在PeopleAddress中,但添加了两个ID为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无法添加记录? 我应该在编辑人员之前手动添加新记录吗?
答案 0 :(得分:0)
异常消息已告诉您该怎么做:
这可能是因为某些实体是新的并且尚未收到数据库生成的键值。 在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图表,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。
换句话说,当您致电PeopleAddress
时,您需要确保每个新的Added
状态为Modified
而非SaveChanges
。这样的事情应该有效
_db.People.Add(people);
_db.Entry(people).State = EntityState.Modified;
foreach(PeopleAddress address in newAdddresses) {
_db.Entry(address).State = EntityState.Unchanged;
}