I'm having a hard time updating entities in Entity Framework.
The scenario: - I load a entity with new DbContext().GetById(guid) - I try to save this entity using a extension method, then using a new DbContext()
Heres my Update method:
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();
}
This is a collection of attemps by me. If I use SetValues I'm told that the entity is detached and therefor not possible, and If I use the attach I get the following error: 'An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.'
I'm obviously doing something fundamentally wrong. Can someone please help me in the right direction?
UPDATE:
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;
}
And the Update() method you see in my original post...
ClubHelpercreates a new context,GetClubloads an existing club from the DB andAddUseris supposed to create a new user, insert it into the DB and set a reference to the club, right?