当我们使用Entity框架同时插入多行时,最好逐个添加这些对象,然后在最后提交,而不是每次都添加和调用。
那么在这种情况下,我如何获得这些插入的ID?
示例:
foreach (var item in list)
{
Subscription subscription = new Subscription();
subscription.Amount = item.ItemTotal;
this.ClientRepositories.LiveData.AddToSubscriptions(subscription);
// LiveData is db context via webservice proxy
// how to get IDS of these insertions if you do not commit each time?
int id = subscription.Id;
someOtherOperation(id); //i need to insert ID for each row that was inserted
}
this.ClientRepositories.LiveData.SaveChanges();
如果我在每次添加新对象时使用内部提交,我可以很容易地获得最新插入的ID,但是每次为我听到的多行提交都不好。
答案 0 :(得分:2)
我假设你正在使用自动增加的id。我认为您必须在循环之外保留订阅对象的列表。在每次循环迭代期间,将当前订阅添加到列表中。执行'SaveChanges();'之后订阅ID将自动添加。
看起来像这样:
List<Subscription> subList = new List<Subscription>();
foreach (var item in list)
{
Subscription subscription = new Subscription();
subscription.Amount = item.ItemTotal;
this.ClientRepositories.LiveData.AddToSubscriptions(subscription);
subList.add(subscription);
}
this.ClientRepositories.LiveData.SaveChanges();
/* At this point, each Subscription in your 'subList' should have an id */