c# – 实体框架可以使用单个SaveChanges()添加许多相关实体吗?

我正在向数据库编写许多(20)个父子数据集,并且EF要求我在每个集合之间保存更改,否则它会抱怨无法找出主键.可以将数据刷新到SQL Server,以便EF可以从身份中获取主键,并在写入所有更改结束时发送SaveChanges吗?

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

我想在大循环结束时只做一次我的SaveChanges.

最佳答案
如果您使用对象引用新创建的对象而不是ID,则不需要每次都保存更改:

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

转载注明原文:c# – 实体框架可以使用单个SaveChanges()添加许多相关实体吗? - 代码日志