正确的方法使用LINQ到实体插入多条记录到表 [英] The right way to insert multiple records to a table using LINQ to Entities

查看:610
本文介绍了正确的方法使用LINQ到实体插入多条记录到表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我们很多人都做了,我成立了一个简单的循环,从一个DATABSE添加多个记录。典型的一个例子是这样的:

As many of us have done, I set up a simple loop to add multiple records from a databse. A prototypical example would be something like this:

// A list of product prices
List<int> prices = new List<int> { 1, 2, 3 };

NorthwindEntities NWEntities = new NorthwindEntities();

foreach (int price in prices)
{
   Product newProduct = new Product();
   newProduct.Price = price;
   NWEntities.Products.AddObject(newProduct);
}

NWEntities.SaveChanges();

当我第一次设立了环,但是,我直觉地写道:

When I first set up the loop, however, I intuitively wrote:

Product newProduct = new Product();

foreach (int price in prices)
{
   newProduct.Price = price;
   NWEntities.Products.Add(newProduct);
}

做了一些阅读后,几个人提到,如果在方法II 只使用一个记录将被添加到表。这似乎直觉。这是Add()函数它加载一个新的插入,并且我认为,每次通话与传递的数据后,创建一个对象。声明我的产品对象的 的外循环似乎更好地利用资源作为消耗每个呼叫的唯一的开销将是重新分配的对象实例属性的,而不是重新构造中的物体实例本身。

After doing a little reading, several individuals mentioned that if the Method II is used only one record would be added to the table. This seems counter intuitive. It's the Add() function which load a new insertion, and, I would think, creates an object after each call with the data passed in. Declaring my Product object outside the loop would seem to better utilize resources, as the only overhead consumed in each call would be the re-assignment of the object instance property, and not the re-construction of the object instance itself.

任何人都可以请你澄清?我找不到另外一个职位,直接这个问题的处理。如果一个人在那里,请指向它。

Can anyone please clarify? I could not find another post that deals with this question directly. If one is out there please point to it.

推荐答案

只需将循环内的新产品的实例。因为它是写将添加一个实例,它不会产生你是什么后...你需要每个产品的一个单独的实例多次... Add方法不会使副本你的code,它重视的反对的背景下,并将其标记为插入。

Simply move the instantiation of the new Product inside the loop. Your code as it is written will add a single instance multiple times which does not produce what you are after...you need a separate instance of each product...the Add method does not make a copy, it attaches the object to the context and marks it for insertion.

foreach (int price in prices)
{
   Product newProduct = new Product();
   newProduct.Price = price;
   NWEntities.Products.Add(newProduct);
}

要看看发生了什么事有点更明确地考虑以下内容:

To see what is happening a bit more explicity consider the following:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Try to reuse same Instance:");
        using (var ctx = new AdventureWorksEntities())
        {
            List<int> ids = new List<int> {1, 2, 3}; 
            Product p1 = new Product();
            Product reference = p1;
            Product p2;
            Console.WriteLine("Start Count: {0}", ctx.Products.Count());
            foreach (var id in ids)
            {
                p1.ProductID = id;
                p2 = ctx.Products.Add(p1);
                Console.WriteLine("p1 = p2 ? {0}", p1 == p2);
                Console.WriteLine("p2 = reference? {0}", p2 == reference);
                Console.WriteLine("State: {0}", ctx.Entry(p1).State);
                var changes = ctx.ChangeTracker.Entries<Product>();
                Console.WriteLine("Change Count: {0}", changes.Count());
            }
        }
        Console.WriteLine();
        Console.WriteLine("Distinct Instances:");
        using (var ctx = new AdventureWorksEntities())
        {
            List<int> ids = new List<int> { 1, 2, 3 };
            Product p2;
            foreach (var id in ids)
            {
                var p1 = new Product {ProductID = id};
                p2 = ctx.Products.Add(p1);
                Console.WriteLine("p1 = p2 ? {0}", p1 == p2);
                Console.WriteLine("State: {0}", ctx.Entry(p1).State);
                var changes = ctx.ChangeTracker.Entries<Product>();
                Console.WriteLine("Change Count: {0}", changes.Count());
            }
        }

        Console.ReadLine();
    }
}

在第一循环要重复使用相同的产品实例,但是当你将它添加到上下文你只是用相同的参考各一次。你可以看到,改变计数仍无论循环多少次执行1。当然,只有最后的值会如果你调用ctx.SaveChanges()保存。

In the first loop you are reusing the same product instance, but when you add it to the context you are just using the same reference each time. You can see that the change count remains at 1 regardless of how many times the loop is executed. Of course only the last values would be saved if you were to call ctx.SaveChanges().

在第二个版本,改变计数是否正确时加一,你会调用的SaveChanges会保存所有不同的实体,如你所愿。

In the second version, the change count is correctly incremented each time and you would be calling SaveChanges would save all of distinct entities as you would expect.

这篇关于正确的方法使用LINQ到实体插入多条记录到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆