我很难在实体框架中更新实体。
场景: - 我使用 new DbContext().GetById(guid) 加载实体 - 我尝试使用扩展方法保存该实体,然后使用 new DbContext()
这是我的更新方法:
public virtual void Update(IEntity entityToUpdate)
{
var dbEntry = Context.Entry(entityToUpdate);
if (dbEntry == null) return;
if (Context.Entry(entityToUpdate).State == EntityState.Detached)
DbSet.Attach(entityToUpdate);
else
{
dbEntry.CurrentValues.SetValues(entityToUpdate);
Context.Entry(entityToUpdate).State = EntityState.Modified;
}
Context.SaveChanges();
}
这是我的尝试集合。如果我使用 SetValues,我会被告知实体已分离,因此不可能,如果我使用附加,则会收到以下错误:'ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。
我显然在做一些根本错误的事情。有人可以在正确的方向上帮助我吗?
更新:
protected void TransferClubs(object sender, EventArgs e)
{
var clubHelper = new ClubHelper();
var club = clubHelper.GetClub(new Guid("A009D0CD-71C4-42E8-88E2-037F059B12EE"));
club.AddUser(Guid.NewGuid(), ClubRoleType.Admin);
club.AddUser(Guid.NewGuid(), ClubRoleType.Admin);
club.Save();
}
public static bool Save(this ClubItem item)
{
var clubHelper = new ClubHelper();
clubHelper.AddOrUpdate(item);
return true;
}
public ClubItem AddOrUpdate(ClubItem item)
{
if (item.Id == Guid.Empty)
Insert(item);
else
Update(item);
return item;
}
还有你在我原来的帖子中看到的 Update() 方法......