繁体   English   中英

如何正确更新(添加/更新/删除)实体的相关数据(EF Core)

[英]How to properly update (add/update/remove) related data of entity (EF Core)

我有以下简化模型(使用 FluentAPI 配置以工作 MS SQL 表):

CV:
   int ID
   string Title
   List<SkillCV> SkillsCVs // many-to-many junction/associative model/table to link the 2 tables

SkillCV:
   int CvID
   int SkillID
   bool IsCore

Skill:
   int ID
   string Title

我使用注入到服务中的存储库模式,该服务注入到 API controller 中。 所以我将逻辑直接简化成一个服务方法:

public async Task<int> UpdateAsync(CV cv)
{
   var cvDB = await context.Set<CV>()
               .Include(CV => CV.SkillsCVs)
                  .ThenInclude(skillCV => skillCV.Skill)
               .Include(CV => CV.User)
               .FirstOrDefaultAsync(CV => CV.Id == cv.Id);
   cvDB.Title = cv.Title;
   SkillCV[] skillsCVs = ...; // I get this with SemaphoreSlim, because it has concurrency issues with async lambda in LINQ method
   // assume that I have the "new" SkillCV array of entities that I need to replace the old ones with
   
   // cvDB.SkillsCVs = skillsCVs.ToList(); // many exceptions here
   UpdateSkills(cvDB, skillsCVs);
}

如何用新的技能CVs 列表替换旧的 cvDB.SkillsCVs 列表? 当两个列表相等(具有相同值的相同实体)时,我得到“已经具有 id... 的附加技能”异常。 如果旧的 cvDB.SkillsCVs 数组为空,它会毫无问题地添加新实体。 如何解决未更改/已删除状态的问题。 我需要一种用新列表更新列表的方法。

   public UpdateSkills(CV cv, List<SkillsCV> newSkillsCVs)
   {
      var oldSkillsCVs = cv.SkillsCVs;
      // how to replace oldSkillsCVs with newSkillsCVs
   }

你能帮我用这个方法吗? 我拥有简历中的所有内容

必须有更好的方法,但我现在能想到的,

if(cv.SkillsCVs != null || cv.SkillCVs.Count != 0)
   context.Entry(cv.SkillsCVs).State = EntityState.Detached;
     
cv.SkillsCVs = newSkillsCVs;

您应该清除集合 cv.SkillsVCs,然后用 newSkillsCVs 填充它:

cv.SkillsCVs.Clear();
cv.SkillsCVs.AddRange(newSkillsCVs);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM