Closed
Description
I have an set of POCOs that are set up like this:
public class Parent {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ParentID { get; set; }
[ForeignKey("ChildAID")]
public ChildA ChildA { get; set; }
[ForeignKey("ChildBID")]
public ChildB ChildB { get; set; }
}
public class ChildA {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ChildAID { get; set; }
[ForeignKey("ChildBID")]
public virtual ChildB ChildB { get; set; }
public long? ChildBID { get; set; }
public string SomeProperty { get; set; }
}
public class ChildB {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ChildBID { get; set; }
public string SomeProperty { get; set; }
}
My problem is that when using BulkInsert on Parent entities that have existing ChildA and ChildB entities, the keys for ChildA and ChildB are not populated on the Parent's table. My code does something like this:
var children = context.ChildA.Where(c => c.SomeProperty.Equals("somestring"));
var parentsToCreate = new List<Parent>();
foreach(var child in children) {
parentsToCreate.Add(new Parent {
ChildA = child,
ChildB = child.ChildB
});
}
dataMatchingContext.BulkInsert(parentsToCreate);
This does insert to the Parent table, but both ChildAID and ChildBID is null. Replacing the BulkInsert call with the code below populates both child IDs properly but is obviously slow.
dataMatchingContext.AddRange(parentsToCreate)
dataMatchingContext.SaveChanges();