Is there a way to do an insert/select with Linq that translates to this sql:
INSERT INTO TableA (...)
SELECT ...
FROM TableB
WHERE ...
When using LINQ to SQL, you insert new records by calling the InsertOnSubmit() method. After calling the InsertOnSubmit() method, you must call SubmitChanges() to make the insertion happen.
INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.
LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.
LinqConnect is a lightweight, LINQ to SQL-compatible ORM solution with support for MySQL, Oracle, PostgreSQL, and SQLite.
Yes @bzlm covered it first, but if you prefer something a bit more verbose:
// dc = DataContext, assumes TableA contains items of type A
var toInsert = from b in TableB
where ...
select new A
{
...
};
TableA.InsertAllOnSubmit(toInsert);
dc.SubmitChanges();
I kind of prefer this from a review/maintenance point of view as I think its a bit more obvious what's going on in the select.
In response to the observation by @JfBeaulac :
Please note that this will not generate the SQL shown - so far as I'm aware it's not actually possible to generate directly using Linq (to SQL), you'd have to bypass linq and go straight to the database. Functionally its should achieve the same result in that it will perform the select and will then insert the data - but it will round-trip the data from the server to the client and back so may not be optimal for large volumes of data.
context
.TableA
.InsertAllOnSubmit(
context
.TableB
.Where( ... )
.Select(b => new A { ... })
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With