简体   繁体   English

将linq转换为sql到存储过程以进行批量插入

[英]converting linq to sql to stored procedure for bulk insert

I have a L2S query that looks like this: 我有一个L2S查询,看起来像这样:

using (MyDC TheDC = new MyDC())
{
   foreach (MyObject TheObject in TheListOfMyObjects)
   {
      DBTable TheTable = new DBTable();

      TheTable.Prop1 = TheObject.Prop1;
      TheTable.Prop2 = TheObject.Prop2; 
      // only 2 properties, an int and a string

      TheDC.DBTables.InsertOnSubmit(TheTable);
   }
   TheDC.SubmitChanges();
}

How could I change this to a stored procedure that does a bulk insert of the list? 如何将其更改为可批量插入列表的存储过程? I found this article that talks about using a dataset and sqlbulkcopy classes; 我发现这篇文章讨论了如何使用数据集和sqlbulkcopy类。 is this the best way to do it? 这是最好的方法吗?

Thank you for your suggestions and feedback. 感谢您的建议和反馈。

Maybe something like this: 也许是这样的:

void Main()
{
    //Your list of objects
    List<MyObject> TheListOfMyObjects=new List<MyObject>();

    var dt=new DataTable();
    dt.Columns.Add("Prop1",typeof(int));
    dt.Columns.Add("Prop2",typeof(string));
    foreach (var TheObject in TheListOfMyObjects)
    {
        dt.Rows.Add(TheObject.Prop1,TheObject.Prop2);
    }
    InsertWithBulk(dt,"YourConnnectionString","MyObject");
}
private void InsertWithBulk(DataTable dt,string connectionString,string tableName)
{
    using (SqlConnection destinationConnection =new SqlConnection(connectionString))
    {
        destinationConnection.Open();
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
        {
            bulkCopy.DestinationTableName =tableName;

            try
            {
                bulkCopy.WriteToServer(dt);
            }
            catch (Exception ex)
            {
                //Exception from the bulk copy
            }
        }
    }
}

Looks good to me. 对我来说看上去很好。

Quite frankly I'd drop L2S entirely because of it's general horrible performance but you may have an app that is too far along to do that. 坦率地说,我会完全放弃L2S,因为它的性能通常很差,但是您的应用程序可能做不到。

The best option is not to use InsertOnSubmit in your loop. 最好的选择是不要在循环中使用InsertInSubmit。 Try the following. 尝试以下方法。

using (MyDC TheDC = new MyDC())
{
  List<DBTable> TheTables = new List<DBTable>();
  foreach (MyObject TheObject in TheListOfMyObjects)
  {
    DBTable TheTable= new DBTable();  
    TheTable.Prop1 = TheObject.Prop1;
    TheTable.Prop2 = TheObject.Prop2; 
    // only 2 properties, an int and a string
    TheTables.Add(TheTable);
  }
  TheDC.DBTables.InsertAllOnSubmit(TheTables);
  TheDC.SubmitChanges();
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM