Insert list into multiple tables with foreign key relationship Entity Framework

c# entity-framework entity-framework-6 optimization

Popular Answer

You can useAddRange to customise how the Documents list is saved. However, you will still want a method to construct them since each Connector Document row requires its own object. I'd recommend anything along these lines:

using (Entities context = new Entities())
{
    using (var dbContextTransaction = context.Database.BeginTransaction())
    {
        context.Documents.AddRange(documents);
        context.SaveChanges();

        var connectorDocuments = from doc in documents
                                 select new Connector_Document 
                                 {
                                     ConnectorId = connectorId,
                                     DocumentId = doc.DocumentId
                                 };
        context.Connector_Document.AddRange(connectorDocuments);
        context.SaveChanges();
        dbContextTransaction.Commit();
    }
}
2
9/27/2016 3:51:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow