Skip to content

Instantly share code, notes, and snippets.

@RhysC
Created October 16, 2012 01:22
Show Gist options
  • Save RhysC/3896756 to your computer and use it in GitHub Desktop.
Save RhysC/3896756 to your computer and use it in GitHub Desktop.
EF DB Context not persisting Child record
public class Parent
{
public Parent()
{
Children = new HashSet<Child>();
}
public int ParentId { get; set; }
public string Name { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int ChildId { get; set; }
public string Name { get; set; }
}
public class SampleContext : System.Data.Entity.DbContext
{
public System.Data.Entity.DbSet<Parent> Parents { get; set; }
}
public class SampleRunner
{
//Entry point of app
public static void Run()
{
var parent = new Parent { Name = "barry" };
parent.Children.Add(new Child { Name = "william" });
using (var context = new SampleContext())
{
context.Parents.Add(parent);
context.SaveChanges();
}
using (var context = new SampleContext())
{
foreach (var p in context.Parents)
{
Console.WriteLine("Parent name: {0}, id :{1}", p.Name, p.ParentId);
Console.WriteLine("Children:");
foreach (var c in p.Children)
{
Console.WriteLine("\t{0}", c.Name);
}
}
}
}
}
@RhysC
Copy link
Author

RhysC commented Oct 16, 2012

RESULT : The data was being saved however i was not appropriately retrieving the data - either needs to be lazy loaded by marking the Children prop as virtual or eager load on retrieval (.Include())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment