【问题标题】:how did EF chose the order of the add operationsEF如何选择添加操作的顺序
【发布时间】:2015-07-25 20:59:12
【问题描述】:

我正在开发一个 asp.net mvc Web 应用程序 + Entity Framework 6.0。我已经使用 EF Db-Context 在我的 Web 应用程序中映射了我的数据库表。我有两个模型类 Emp & Dept 如下:-

public partial class Dept
    {

        public Dept()
        {
            this.Emps = new HashSet<Emp>();
        }

        public int DeptID { get; set; }
        public string DName { get; set; }


        public virtual ICollection<Emp> Emps { get; set; }
    }
//----
  public partial class Emp
    {
        public Emp()
        {
            this.Accounts = new HashSet<Account>();
        }

        public int EMPID { get; set; }
        public string name { get; set; }
        public int DeptID { get; set; }

        public virtual Dept Dept { get; set; }

        public virtual ICollection<Account> Accounts { get; set; }
    }

现在需要Emp.DeptID FK,所以我编写了以下测试方法来测试 EF 是否足够聪明以重新排序添加操作:-

public ActionResult Index()
        {

            Dept d = new Dept() { DName="test5"};
            Emp e = new Emp() { name="test5test5"};
            t.Emps.Add(e);



            d.Emps.Add(e);
            t.Depts.Add(d);

            t.SaveChanges();
            return Content("5");
        }

现在我虽然上述方法会引发异常,因为我已经定义在添加部门之前添加t.Emps.Add(e);,这应该引发 Emp.DeptID 不能为零的异常(因为没有任何部门与零身份)。但实际发生的情况是 Dept 和 Emp 都被添加了,所以我的问题是 EF 是如何处理上述方法的?唯一有效的方法是 EF 先添加了部门,这与我指定的顺序不同?

【问题讨论】:

    标签: c# entity-framework entity-framework-6 dbcontext


    【解决方案1】:

    EF 总是会弄清楚如何以正确的顺序执行 SQL 语句,无论是插入、更新还是删除,无论它们如何混合。您唯一的任务是在内存中构建对象结构(或“图表”),并将对象标记为已添加/已更新/已删除,您可以按任何顺序进行操作。

    如果我们必须注意以正确的顺序创建和附加对象,我会很麻烦。当应用程序变得有点复杂时,这几乎是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多