Created
October 16, 2012 01:22
-
-
Save RhysC/3896756 to your computer and use it in GitHub Desktop.
EF DB Context not persisting Child record
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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())