本文介绍了要在Entity Framework中编辑多对多关系,为什么必须首先清除该集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来编辑用户所在的部门.出于某种原因, method1 导致EF尝试再次插入关系(并导致主键错误),其中 method2 成功.

I have the following code for editing the departments a user is in. For some reason, method1 causes EF to try and insert the relationship again (and causing a primary key error), where method2 succeeds.

为什么 method1 的代码不知道通过重新分配值,我只想要新的部门集合? method2 是更新值的首选方法吗?我不必在一对多关系中采用这种方式.

Why does the code of method1 not know that by reassigning the value, I only want the new collection of departments? Is method2 the preferred method to update values? I haven't had to do it this way with one to many relationships.

public class User
{
    public string name { get; set; }
    public virtual List<Department> Departments { get; set; }
}

public class Department
{
    public string name { get; set; }
    public virtual List<User> Users { get; set; }
}

public void Method1(list<Department> departments, string userId)
{
    var user = DbContext.Users.FirstOrDefault(u=> u.Id == userId);
    user.departments = departments;
    db.SaveChanges()
}

public void Method2(list<Department> departments, string userId) 
{
    var user = DbContext.Users.FirstOrDefault(u=> u.Id == userId);
    user.departments.clear();
    user.departments = departments;
    db.SaveChanges()
}

推荐答案

部门下方,我的意思是 Users2Departments 表.

Below on departments, I will mean Users2Departments table.

可能是因为您在编写 user.departments.clear(); 时加载了所有相关的部门(通过 LazyLoading ),因此它们可以被 EF 跟踪,并被成功标记为 Deleted (在 clear()调用之后).然后将新的部门分配给 user ,即标记为 Added .一切正确.

Probably, it happened because, when you wrote user.departments.clear(); you loaded all related departments(via LazyLoading), so they become trackable by EF and were successfully marked as Deleted(after clear() call). And then new departments were assigned to user, i.e. marked as Added. All is correct.

但是,如果仅执行分配: user.departments =部门,则 EF 将不知道或不在乎,因为存在部门,并且应该删除它们,因为至少 user.departments 文字位于 Left HandSide( user.departments.clear() HandSide).而且 Users2Departments 表是隐式表.因此, EF 仅插入新的部门而不会删除以前的部门,因此可能会发生异常.

But, if you just perform only assigning: user.departments = departments, EF will not know or not care, that there are existed departments and it should delete them, because, at least, they are not tracked, because they not loaded, since user.departments literal is located at LeftHandSide(user.departments.clear() is RightHandSide). Moreover Users2Departments table is implicit table. So EF only inserts new departments without deletion of previous ones, so exception will may occur.

这篇关于要在Entity Framework中编辑多对多关系,为什么必须首先清除该集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:22