Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do an INSERT with a SELECT equivalent in Entity Framework 4

I'm migrating an application from SqlClient to the Entity Framework 4, working with SQL Server. I have a situation where I have to copy several rows from one table to another, so I do it with an INSERT ... SELECT, as below:

INSERT INTO dbo.Table1 (Reg1, Reg2, Reg3, Reg4, Reg5, Reg6, Reg7, Reg8)
SELECT Reg1, Reg2, Reg3, Reg4, Reg5, @Reg6, GETDATE(), @Reg8
FROM dbo.Table2 
WHERE Reg1 = @Reg1

Can I accomplish something remotely similar to this with the Entity Framework, or would I have to get all of the rows from Table2, and insert them row by row in Table1? How could I handle the GETDATE()?
Tks

like image 780
Pascal Avatar asked Jan 13 '11 19:01

Pascal


2 Answers

Put the sql in a stored procedure, and then call that stored procedure from your app - I'd just use plain sql client to make the call to execute the proc, but no reason you can't map it into your EF model if you really wanted to and then call it from EF.

You can have it return a value if you want/need to.

like image 148
E.J. Brennan Avatar answered Oct 28 '22 06:10

E.J. Brennan


No this will not work in EF. EF will load all selected data from DB to your application materializing them as objects and insert these objects one by one to second table. EF is unable to do batch operations at all.

like image 41
Ladislav Mrnka Avatar answered Oct 28 '22 08:10

Ladislav Mrnka