Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - Can Entity Framework add many related entities with single SaveChanges()?

I am writing many (20+) parent child datasets to the database, and EF is requiring me to savechanges between each set, without which it complains about not being able to figure out the primary key. Can the data be flushed to the SQL Server so that EF can get the primary keys back from the identities, with the SaveChanges being sent at the end of writing all of the changes?

foreach (var itemCount in itemCounts)
{
    var addItemTracking = new ItemTracking
    {
        availabilityStatusID = availabilityStatusId,
        itemBatchId = itemCount.ItemBatchId,
        locationID = locationId,
        serialNumber = serialNumber,
        trackingQuantityOnHand = itemCount.CycleQuantity
    };
    _context.ItemTrackings.Add(addItemTracking);
    _context.SaveChanges();
    var addInventoryTransaction = new InventoryTransaction
    {
        activityHistoryID = newInventoryTransaction.activityHistoryID,
        itemTrackingID = addItemTracking.ItemTrackingID,
        personID = newInventoryTransaction.personID,
        usageTransactionTypeId = newInventoryTransaction.usageTransactionTypeId,
        transactionDate = newInventoryTransaction.transactionDate,
        usageQuantity = usageMultiplier * itemCount.CycleQuantity
    };
    _context.InventoryTransactions.Add(addInventoryTransaction);
    _context.SaveChanges();
}

I would like to do my SaveChanges just once at the end of the big loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don`t need to save changes every time if you use objects refernces to newly created objects not IDs:

var addItemTracking = new ItemTracking
{
    ...
}
_context.ItemTrackings.Add(addItemTracking);
var addInventoryTransaction = new InventoryTransaction
{
    itemTracking = addItemTracking,
    ...
};
_context.InventoryTransactions.Add(addInventoryTransaction);
...
_context.SaveChanges();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...