我有一个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类;这是最好的方法吗?
感谢您的建议和反馈。
答案 0 :(得分: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
}
}
}
}
答案 1 :(得分:0)
对我来说很好看。
坦率地说,我完全放弃了L2S,因为它的性能非常糟糕,但你可能有一个应用程序太远了。
答案 2 :(得分:0)
最好的选择是不要在循环中使用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();
}
希望这有帮助。