Assuming I have the below table/class structure for Entity Framework Core. Is it possible to insert new records with a join table in one call to SaveChanges?
I know it can be done with 2 saves (insert TableB > save > insert TableAB > save) and there's a similar question doing that.
public class TableA
{
public int Id { get; set; }
public ICollection<TableAB> ABs { get; set; } = null!;
}
public class TableAB
{
public int TableAId { get; set; }
public TableA TableA { get; set; } = null!;
public int TableBId { get; set; }
public TableB TableB { get; set; } = null!;
}
public class TableB
{
public int Id { get; set; }
}
CodePudding user response:
It's quite easy to insert multiple related objects with only one save - for example:
var b1 = new TableB();
var b2 = new TableB();
context.TableAs.Add(new TableA
{
ABs = new List<TableAB>
{
new TableAB
{
TableB = b1,
},
new TableAB
{
TableB = b2,
},
},
});
context.TableAs.Add(new TableA
{
ABs = new List<TableAB>
{
new TableAB
{
TableB = b1,
},
},
});
context.TableAs.Add(new TableA
{
ABs = new List<TableAB>
{
new TableAB
{
TableB = b2,
},
},
});
context.SaveChanges();
The only slightly complicated part is keeping references to the related entities (TableB) when you need to reference them from multiple places.
This assumes that your Id properties are all IDENTITY columns in the database. If not, you'll need to manually assign them.
