Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert/Select with Linq-To-SQL

Is there a way to do an insert/select with Linq that translates to this sql:

INSERT INTO TableA (...)
SELECT ...
FROM TableB
WHERE ...
like image 468
Lieven Cardoen Avatar asked Jan 17 '10 12:01

Lieven Cardoen


People also ask

Which of the LINQ method is used to insert data into a relational table?

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.

Which is faster insert into or select into?

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.

Is LINQ converted to SQL?

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.

Can I use LINQ with MySQL?

LinqConnect is a lightweight, LINQ to SQL-compatible ORM solution with support for MySQL, Oracle, PostgreSQL, and SQLite.


2 Answers

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.

like image 58
Murph Avatar answered Oct 14 '22 00:10

Murph


context
  .TableA
  .InsertAllOnSubmit(
    context
      .TableB
      .Where( ... )
      .Select(b => new A { ... })
  );
like image 42
bzlm Avatar answered Oct 13 '22 22:10

bzlm