EF5 Many To Many update disconnected scenario

爱⌒轻易说出口 提交于 2019-12-06 01:26:23

SOLUTION I don't know if it's the best, but it works for me and I think it has sense. EF creates a duplicate of the relatedentities because they were detached, I changed my code in this way:

public void AddOrUpdate(MyEntity entity) {
    var dbEntity = _context.MyEntities
      .Include(e => e.RelatedEntitis)
      .Where(e => e.ID == entity.ID)
      .SingleOrDefault();

    //replace entities with those taken from the context
    var relatedEntities = _context.RelatedEntities;
    var detachedEntities = entity.RelatedEntities;
    entity.RelatedEntities = new List<RelatedEntity>();
    foreach (var ent in detachedEntities)
    {
      entity.RelatedEntities.Add(relatedEntities .Where(e => e.ID == hop.ID).SingleOrDefault());
    }

    var newRelated = entity.RelatedEntitis.ToList<RelatedEntity>();
    var dbRelated = dbEntity.RelatedEntity.ToList<RelatedEntity>();

    _context.Entry(dbEntity).CurrentValues.SetValues(entity);
    _context.Entry(dbEntity.RelatedEntity).CurrentValues.SetValues(entity.RelatedEntitis);

    var comparer = new EqualityComparer();
    var addedRelated = newRelated.Except(dbRelated, comparer).ToList<RelatedEntity>();
    var deletedRelated = dbRelated.Except(newRelated, comparer).ToList<RelatedEntity>();

    addedRelated.ForEach(e => dbEntity.RelatedEntity.Add(e));
    deletedRelated.ForEach(e => dbEntity.RelatedEntity.Remove(e));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!