如何编写LINQ to SQL等效于:
INSERT INTO Table1 (field1, field2, field3)
SELECT field1, field2, field3
FROM Table2
WHERE (field1= @field1)
由于
答案 0 :(得分:6)
由于您没有返回任何结果,只需使用低级DataContext.ExecuteCommand()
方法:
using (MyDataContext dc = new MyDataContext())
{
dc.ExecuteCommand(@"
INSERT INTO Table1 (field1, field2, field3)
SELECT field1, field2, field3
FROM Table2
WHERE (field1= {0})
",
field1);
}
答案 1 :(得分:3)
LINQ是一种查询语言,因此它不会进行更新或插入。但是,LINQ to SQL实体对象模型具有处理CUD的方法:
using(MyDataContext dc = new MyDataContext())
{
//select the source entities from Table2
var Table2Entities = (from e in dc.Table2 where e.Field1 == "value" select e);
//for each result, create a new Table1 entity and attach to Table1
Table2Entities.ForEach(t2e => dc.Table1.InsertOnSubmit(
new Table1Entity {
Field1 = t2e.Field1,
Field2 = t2e.Field2,
Field3 = t2e.Field3
});
//submit the changes
dc.SubmitChanges();
}
这里的真正区别在于它需要两个单独的SQL事务而不是一个 - 一个用于选择,一个用于插入。
答案 2 :(得分:0)
如果两个表的字段相同,那么, 使用
insert into table1 select * from table2 where table2.field1='xyz';
取代:
INSERT INTO Table1 (field1, field2, field3)
SELECT field1, field2, field3
FROM Table2
WHERE (field1= @field1)