Cannot update many-to-many relationships in Entity Framework

a 夏天 提交于 2019-12-05 06:04:39

But when I try to delete from Video2 the existing coworkers (B and C), and try to add coworker A, then the relationship is not updated.

Without using a generic repository the correct procedure would be:

using (var session = new DatabaseSession())
{
    video2 = session.Context.Set<Video>().Include(v => v.Coworkers)
        .Single(v => v.Id == video2Id);

    coworkerA = new Coworker { Id = coworkerAId };
    session.Context.Set<Coworker>().Attach(coworkerA);

    video2.Coworkers.Clear();
    video2.Coworkers.Add(coworkerA)

    session.Context.SaveChanges();
}

The essential part is that you must load or attach the entity in its original state, change the entity, i.e. remove and add children, and then save the changes. EF's change detection will create the necessary INSERT and DELETE statements for the link table entries. The simple procedure to set the state to Modified you are trying in your generic Update method is suited only for updating scalar properties - like changing the video title - but won't work for updating relationships between entities.

For solve this problem:

  1. attach the entity to context
  2. load the collection(the collection is not loaded, because )
  3. change the state of entity to modified
  4. save changes

So your code for update should be like this:

public Video Update(Video entity)
{
    //Creates database context. When it disposes, it calls context.SaveChanges()
    using (var session = new DatabaseSession())
    {
        entity = session.Context.Set<Video>().Attach(entity);
        session.Context.Entry(entity).Collection(p => p.Coworkers).Load();
        session.Context.Entry(entity).State = EntityState.Modified;
    }
    return entity;
}

Please refer here to see how to save master detail in asp.net mvc with database first. Hopefully it will give you the idea about the code first. You may also have a look at knokout.js example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!