EF 如何选择添加操作的顺序

how did EF chose the order of the add operations

我正在开发 asp.net mvc 网络应用程序 + 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 不能为零(因为没有任何 ID 为零的部门)。但实际发生的是 Dept 和 Emp 都被添加了,所以我的问题是 EF 是如何处理上述方法的?唯一有效的方法是 EF 首先添加了部门,这与我指定的顺序不同?

EF 将始终弄清楚如何以正确的顺序执行 SQL 语句,无论是插入、更新还是删除,无论它们如何混合。您唯一的任务是在内存中构建一个对象结构(或'graph'),并将对象标记为added/updated/deleted,您可以按任意顺序执行此操作。

如果我们必须按照正确的顺序创建和附加对象,那将是一个很大的麻烦。当应用程序变得有点复杂时,这几乎是不可能的。