views:

195

answers:

2

How do I write a LINQ to SQL equivalent of:

INSERT INTO Table1 (field1, field2, field3)
SELECT field1, field2, field3
FROM Table2
WHERE (field1= @field1)

Thanks

+3  A: 

LINQ is a querying language, so it doesn't do updates or inserts. However -the LINQ to SQL entity object model has methods for handling 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();
}

The real difference here is that it requires two separate SQL transactionsinstead of one - one to select, and one to insert.

Rex M
Do you have any documentation to backup the assertion that all of the insertions take place in one round trip?
Adam Robinson
@Adam nope. Just my memory, which is often faulty. I'll remove that bit 'till it's cleared up one way or the other. Thanks!
Rex M
@Adam, the SQL Profiler tool will shed some light on how LINQ-to-SQL is communicating with the database server and is a good way to measure performance and how well LINQ is constructing its queries and batches.
David Andres
@David: Yes, that's true. I'm not at work right now so I don't have access to it, and my (possibly incorrect) assumption was that LINQ's data access layer dealt with SQL as ADO did, with one command per row.
Adam Robinson
+1  A: 

Since you aren't returning any results, just use the low-level DataContext.ExecuteCommand() method:

using (MyDataContext dc = new MyDataContext())
{
    dc.ExecuteCommand(@"
        INSERT INTO Table1 (field1, field2, field3)
        SELECT field1, field2, field3
        FROM Table2
        WHERE (field1= {0})
        ",
        field1);
}
Brannon