[英]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.