How to execute SQL with Entity Framework?

0

I tried to run a SQL command by Entity Framework , I tried 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 it worked, I'm using Mysql, what's wrong there?

    
asked by anonymous 24.01.2017 / 20:31

1 answer

1

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

Just use DbContext.Database.ExecuteSqlCommand , where DbContext is your context.

You do not need to use the SaveChanges method in this case because the command will already run directly in the database and will not affect EF entities in the context.

Remembering that after executing the command in 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 lifecycle of the application (ie before discarding and restarting the context)

Here are some links to talk about:

24.01.2017 / 20:42