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

entity-framework-6 sql-server

Question

My online application uses EF, and I've come across an odd issue. In my database, I'm attempting to edit a record, however even if thecontext.Database.ExecuteSqlCommand Whenever call returns 1, I then callcontext.SaveChanges() , it returns 0, and the database does not reflect the modifications.

This is the key:

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();
}

Rows equals 1, but Rows 2 equals 0 for some reason while debugging. As though it were unable to commit the modifications to the database.

Any suggestions as to what may be the cause of this?

1
1
7/27/2018 4:58:04 PM

Accepted Answer

The two methods for writing to the database are so unlike from one another.

An object model (created, for instance, in C#) and a relational database model must be kept in sync with one another for an object-relational mapper (ORM) like Entity Framework to function effectively. As a result, it has the ability to monitor object model changes and write such changes to the database.

Some ORMs provide lower-level APIs to communicate with the database as a courtesy. However, none of these functions nor the ORM function communicate with one another.

To put it another way, whatever command isDbContext.Database.ExecuteSqlCommand The change tracker for EF is absolutely unaware of it. The change tracker is useless if C# code does not alter any entity objects. The tracked entity objects are unaffected by the SQL code that was performed.

2
8/1/2018 6:48:14 PM


Related Questions





Related

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