开发者

inserting multiple records through objectset

Is there any way to insert multiple records without a loop if you already have a collection? Granted there is little performance benefit if you commit outside the loop.

I have a context开发者_运维百科 and ObjectSet<Type>. I also have a collection of Type which I want to swap in or concatenate or intersect or what have you for what's in the table. In other words, I don't want to proceed from the below:

foreach (Type r in Collection)
{
    Context.ObjectSet.Add(r);
}
Context.SaveChanges();


You must always use loop. There cannot be any performance benefit in methods like AddCollection or AddRange because these methods usually works on some performance optimization where internal collection is extended for whole range and it is just copied instead of extending collection for each Add call. AddObject does much more then passing data to some internal collection so it still have to process entities one by one.

If you want to optimize performance of database inserts themselves you must move to another solution because EF doesn't have any batch or bulk data modifications. Each record is passed as single insert in separate roundtrip to the database.


You could try creating an extension method to do the looping and adding. see below.

public static class AddHelper 
{


   public void AddAll(this ObjectSet<T> objectSet,IEnumerable<T> items)
   {

        foreach(var item in items)
        {
           objectSet.AddObject(item);

        }

   }

}

Then you could use the code below.

 IEnumerable<EntityName> list = GetEntities(); //this would typically return your list
 Context.ObjectSet.AddAll(list);


I'm looking for the same type of solution.

I have yet to find a way to do it directly with EF, but there is a way to do it. If you create a Stored Procedure that accepts a DataTable as a parameter, you can execute the PROC with Entity Context and pass the table as a parameter.

When you're dealing with thousands or millions of records, this is a lot better than looping through each record to be passed to DB.

Passing Table Valued Parameters to SQL Server Stored Procedures.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜