[英]converting linq to sql to stored procedure for bulk insert
我有一個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();
}
如何將其更改為可批量插入列表的存儲過程? 我發現這篇文章討論了如何使用數據集和sqlbulkcopy類。 這是最好的方法嗎?
感謝您的建議和反饋。
也許是這樣的:
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
}
}
}
}
對我來說看上去很好。
坦率地說,我會完全放棄L2S,因為它的性能通常很差,但是您的應用程序可能做不到。
最好的選擇是不要在循環中使用InsertInSubmit。 嘗試以下方法。
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();
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.