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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With