[英]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.