1

I had some code for inserting some rows that wasn't working:

using (MyDbContext context = new MyDbContext()) {
    foreach (Order o in FormOrders) { //That's a List<T> that got generated based on a web form
        context.Orders.Add(o);
    }
    context.SaveChanges();
}

I finally figured out how to make it work:

foreach (Order o in FormOrders) {
    context.Orders.Add(o);
    context.SaveChanges();
}

However, I realize that's not very efficient. Granted, the most Orders that will ever get inserted at one time is about 40, but I'm still interested in using best practices as much as I can.

I'm guessing code snippit #1 didn't work because o is out of scope of the point that SaveChanges() is called, but I don't understand how this works well enough to be sure, and I definitely don't understand it enough to figure out what a better way is.

Also, I have heard that you're supposed to use a new instance of your DbContext for every row, which would be even less efficient to implement in the above case. Is that true?

EDIT

忽略这个问题。两个版本似乎都有效。我不知道是什么问题。我不会删除它,因为其他人可能会发现某些评论/答案很有用。

4

2 回答 2

0

我想你在这里处理闭包。

试试这个代码是否适合你:

using (MyDbContext context = new MyDbContext())
{
    foreach (Order o in FormOrders)
    {
        Order localCopy = o;
        context.Orders.Add(localCopy);
    }
    context.SaveChanges();
}

简而言之,您的 Add() 方法将只执行一次。由于延迟执行,只会添加循环的最后一项。

(引自 Jon 的文章链接如下)

什么是闭包?

简单地说,闭包允许你封装一些行为,像任何其他对象一样传递它,并且仍然可以访问它们首次声明的上下文。这允许您将控制结构、逻辑运算符等与它们将如何使用的细节分开。访问原始上下文的能力是将闭包与普通对象区分开来,尽管闭包实现通常使用普通对象和编译器技巧来实现这一点。

专家们会比我更好地解释这一点:

于 2012-11-28T21:18:39.687 回答
0

我不知道您使用的是哪个上下文,但鉴于乐观并发冲突,LINQ to SQL SubmitChanges 的行为与 LINQ to Entitie 的 SaveChanges 不同。

SubmitChanges = DataContext
SaveChanges = ObjectContext

using (MyDbContext context = new MyDbContext()) {
    foreach (Order o in FormOrders) { //That's a List<T> that got generated based on a web form
        context.Orders.Add(o);
    }
    context.SubmitChanges();
}
于 2012-11-28T20:52:29.000 回答