Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EF 4.1 Inserting a parent record and multiple child records as a single "Unit of Work"

I am practicing with a code-first set of classes with a parent-child relationship between them.

public class Parent
{
    public int Id ( get; set; }
    public string Name { get; set; }
    public List<Child> Children { get; set; }

    public Parent()
    {
        Children = new List<Child>();
    }
}

public class Child()
{
    public int Id ( get; set; }
    public string Name { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }
}

In a simple console app I create a parent and create two child records and add them to the parent. If I then call the SaveChanges() only the first child is added to the children table.

var x = new MyContext();

var c1 = new Child { Name = "Alpha-Child" };
var c2 = new Child { Name = "Beta-Child" };

var p = new Parent {Name = "Alpha-Parent"};

p.Children.Add(c1);
p.Children.Add(c2);

x.Parents.Add(p);

x.SaveChanges();

Well that was not what I wanted, so I tried to maybe add then to both the parent object and the context object.

var x = new MyContext();

var c1 = new Child { Name = "Alpha-Child" };
var c2 = new Child { Name = "Beta-Child" };

var p = new Parent {Name = "Alpha-Parent"};

p.Children.Add(c1);
p.Children.Add(c2);

x.Children.Add(c1);
x.Children.Add(c2);

x.Parents.Add(p);

x.SaveChanges();

That got both the child records into the database, but only one of them (the first) was associated with the parent record.

Last, but not least, I tried to do a call to SaveChanges() after each call to Parent.Add().

var x = new MyContext();

var c1 = new Child { Name = "Alpha-Child" };
var c2 = new Child { Name = "Beta-Child" };

var p = new Parent {Name = "Alpha-Parent"};

x.Parents.Add(p);

p.Children.Add(c1);
x.SaveChanges();

p.Children.Add(c2);
x.SaveChanges();

But, this breaks my idea of how the "Unit of Work" Pattern works. I "Should be able to call SaveChanges() once, and have all my changes take place, correct?

So, what am I doing wrong?

like image 559
saunderl Avatar asked Feb 20 '12 02:02

saunderl


1 Answers

The following piece of code will save in single save changes. And always use a transactionscope to save in single batch.

public class Child 
{
  public int Id ( get; set; }
  public string Name { get; set; }
  public Parent Parent {set;get;}
}


var x = new MyContext();
var c1 = new Child { Name = "Alpha-Child" };
var c2 = new Child { Name = "Beta-Child" };

var p = new Parent {Name = "Alpha-Parent"};
c1.Parent = p;
c2.Parent = p;
x.Parents.Add(p);
x.SaveChanges();
like image 193
VIJAY Avatar answered Sep 22 '22 14:09

VIJAY