Skip to content

BulkInsert does not populate foreign keys for child entities #95

Closed
@jaybz

Description

@jaybz

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();

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions