0

What I want to achieve is to only UPDATE particular property of an entity in the Db. (To mimic something like UPDATE Foo Set Status = 'kool' WHERE ID = 99).

I try this:

    public void SetFooStatus(Foo foo)
            {

                var fooToUpdate = new Foo()
                {
                    Id = foo.Id,
                    Status =foo.Status
                };

                this.Context.Foos.Attach(fooToUpdate);

                this.Context.Entry(fooToUpdate).Property("Status").IsModified = true;

                this.Context.ValidateOnSaveEnabled = false;

                this.dbSet.Attach(entityToUpdate); // This is IDbSet<Foo>
                this.dbSet.Entry(entityToUpdate).State = EntityState.Modified;

                this.dbSet.SaveChanges();

            }

Problem is when I set State to EntityState.Modified, all the properties are marked as Chagned -IsModified returns true-.

When I comment it out, then Update is not accomplished -no changes occur in the Db.

Question: How can I enforce EF to UPDATE only the Status property of the foo object without touching other fields in the Db?

pencilCake
  • 51,323
  • 85
  • 226
  • 363

1 Answers1

0

EF does not allow updating a single column. Instead of attaching an entity you may want to fetch it from the server which will set all the fields to the values you have on the server and therefore you won't change other properties. You probably want to use DbSet.Find() method which will try to find an entity by its id in the context and if one does not exist will fetch it from the database.

Pawel
  • 31,342
  • 4
  • 73
  • 104