John John
John John

Reputation: 1

how did EF chose the order of the add operations

I am working on an asp.net mvc web application + Entity Framework 6.0. I have mapped my database tables inside my web application using EF Db-Context. I have two model classes Emp & Dept as follow:-

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

now the Emp.DeptID FK is required , so i wrote the following test method to test if EF will be smart enough to re-order the add operations:-

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

now i though that the above method will raise an exception since i have define to add the t.Emps.Add(e); before adding the dept and this should raise an exception that Emp.DeptID can not be zero (since there is not any Dept with zero id). but what actually happened is that both the Dept & Emp were added ,, so my question is how did EF handle the above method ?, the only valid approach is that EF has added the dept first, unlike the order i specified ?

Upvotes: 0

Views: 141

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109185

EF will always figure out how to execute SQL statements in the right order, whether it's inserts, updates or deletes and no matter how they are mixed. Your only task is to build an object structure (or 'graph') in memory, and mark the objects as added/updated/deleted, which you can do in any order.

I would be a major hassle if we had to take care of creating and attaching objects in the right order. That's almost impossible when an application gets even a little bit complex.

Upvotes: 1

Related Questions