Search code examples
c#linqado.netentities

ADO.NET Entity Model Update


Hi i am trying to update a record from the database, but for some reason the record is not updated. I am using ADO.NET entity Framework 4.0

public void updateCredits(string username)
 {
     myDBEntities Entity = new myDBEntities();
     User u = Entity.Users.SingleOrDefault(u => u.username == username)
     u.firstname = "name";
     u.credits = 11.5;
     Entity.SaveChanges();
 }

I tried restarting VS and even the SQL Server but no luck. Am i doing something wrong?


Solution

  • It looks like there is an issue with change tracking. You can try manually marking the User entity as changed like so:

    public void updateCredits(string username)
     {
         myDBEntities Entity = new myDBEntities();
         User u = Entity.Users.SingleOrDefault(u => u.username == username)
         u.firstname = "name";
         u.credits = 11.5;
         Entity.Entry(u).State = EntityState.Modified;  //<-- manually indicate the entity was changed
         Entity.SaveChanges();
     }
    

    If the above code works, then there's a good chance ChangeTracking is being disabled somehow.