【问题标题】:converting linq to sql to stored procedure for bulk insert将 linq 转换为 sql 以存储过程以进行批量插入
【发布时间】:2012-02-10 22:30:10
【问题描述】:

我有一个如下所示的 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();
}

如何将其更改为对列表进行批量插入的存储过程?我发现这个article 谈到了使用数据集和 sqlbulkcopy 类;这是最好的方法吗?

感谢您的建议和反馈。

【问题讨论】:

    标签: c# sql sql-server linq-to-sql stored-procedures


    【解决方案1】:

    可能是这样的:

    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
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我觉得不错。

      坦率地说,我会完全放弃 L2S,因为它的性能一般都很糟糕,但你可能有一个应用程序太远了,无法做到这一点。

      【讨论】:

        【解决方案3】:

        最好的选择是不要在循环中使用 InsertOnSubmit。请尝试以下操作。

        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();
        }
        

        希望这会有所帮助。

        【讨论】:

        • 这行不通。因为 InsertAllOnSubmit 需要一个表实体列表。执行 InsertOnSubmit 时,它不会向数据库插入任何内容。这将在调用 SubmitChanges 时发生。因此,请更新您的答案或将其删除。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-14
        • 1970-01-01
        相关资源
        最近更新 更多