How to run SQL with Entity Framework?

Asked

Viewed 455 times

0

I tried to execute a command SQL for Entity Framework, tried in the following ways:

string cmd = "UPDATE t0071_compra SET t0071_status = 'Enviado' WHERE t0071_id_compra = 4 AND t0020_id_empresa = 1";
context.Database.SqlQuery<string>(cmd);
context.SaveChanges();

string cmd = "UPDATE t0071_compra SET t0071_status = 'Enviado' WHERE t0071_id_compra = 4 AND t0020_id_empresa = 1";
context.Database.ExecuteSqlCommand(cmd);
context.SaveChanges();

but in none of the ways worked, I’m using Mysql, what’s wrong there?

  • Do you have an error? if it is UPDATE is the second way!

  • has no error, but has no effect

  • alessandre is very strange, have no effect, maybe does not satisfy the condition! check if returns int rows = context.Database.ExecuteSQLCommand(cmd) higher than 0, if return it updated something if returned 0 it had no change?

1 answer

1


If you want to execute a command that does not return results (it is not a SELECT)

just use DbContext.Database.ExecuteSqlCommand, where Dbcontext is your context.

The method need not be used SaveChanges in this case, because the command will already run directly in the bank and will not affect the EF entities in the context.

Remember that after executing the command this way you need to update the entities manually (via DbContext.Entry(entity).Reload();) if you want to use the updated values in the same application Lifecycle (i.e., before discarding and restarting the context)

Here are some links talking about:

  • so, the way I used it, it should work, I tested without saveChanges, but tb didn’t work

  • Did you manually check in the database ? Where is right ? Run the direct command in Mysql and see if it updates

Browser other questions tagged

You are not signed in. Login or sign up in order to post.