EF更新报错
An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same key.
DbSet已经加载过一次对象了,当试图去attach另一个相同ID的对象的时候EF就会报错。
var user = userList.Where<UserAccountEntity>(p => p.Account == row["account"].ToString()).FirstOrDefault(); if (user != null) { if (user.RealName != row["name"].ToString() || user.Note != row["OU"].ToString()) { // 更新用户 updateUser.Add(Table2User(row,user.ID)); } }
private UserAccountEntity Table2User(DataRow row,int id) { return new UserAccountEntity { ID = id, Account = row["account"].ToString(), RealName = row["name"].ToString(), SubSystem = "AD", Note = row["OU"].ToString() }; }
原因:更新的对象不能是new的对象,而应该是原来的uesr对象
所以修改方案是:
var user = userList.Where<UserAccountEntity>(p => p.Account == row["account"].ToString()).FirstOrDefault(); if (user != null) { if (user.RealName != row["name"].ToString() || user.Note != row["OU"].ToString()) { user.RealName = row["name"].ToString(); user.Note = row["OU"].ToString(); // 更新用户 updateUser.Add(user); } } base.DBAction.Update<UserAccountEntity>(updateUser.ToArray());