如何正确更新(添加/更新/删除)实体(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 控制器中的服务的存储库模式。因此,我将直接将逻辑简化为服务方法:

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);
}

如何将旧的 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.SkillsVC,然后用newSkillsCVs填充它:

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

最新更新