Entitiy Framework context.Database.ExecuteSqlCommand won't save changes to DB

entity-framework-6 sql-server


I am using EF for my web application and have encountered a strange error. I am trying to update a record in my DB, but even though the context.Database.ExecuteSqlCommand call returns 1, when I then call context.SaveChanges(), it returns 0 and the changes are not visible in the database.

Here is the code:

List<int> ids = new List<int> { 1, 2, 3 };

using (var context = new TestDbContext())
    int rows=context.Database.ExecuteSqlCommand("UPDATE [Records] SET [ExampleFlag] = 1 WHERE Id in (@ids)",new SqlParameter("@ids",String.Join(",", ids)));
    int rows2 = context.SaveChanges();

For some reason when debugging, rows equals 1, but rows 2 equals 0. As if it couldn't commit the changes to the database.

Any ideas on what may cause this?

7/27/2018 4:58:04 PM

Accepted Answer

These two ways to write to the database are almost two different worlds.

The core function of an Object-Relational Mapper (ORM) like Entity Framework is to keep an object model (for example in C#) and a relational database model in sync with one another. Therefore it is capable of tracking changes in the object model and writing these changes to the database.

Some ORM's, as a kind of courtesy, offer lower-level APIs to interact with the database. However, these functions don't interact with the ORM function, vise versa.

In other words, whatever statement is executed by DbContext.Database.ExecuteSqlCommand, EF's change tracker is completely oblivious of it. If no entity objects were modified by C# code, the change tracker has nothing to do. The executed SQL code has no effect on tracked entity objects.

8/1/2018 6:48:14 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow