PiousVenom
PiousVenom

Reputation: 6918

Database isn't being updated

I've just started using Entity, and so far, it's made my life infinitely easier. However, when I try to update a row, this is where I run into issues. Googling brought me to the Attach(), to which I've tried:

public void Update()
{
    using (var context = new HDDCContainer())
    {
        context.Projects.Attach(this);
        context.SaveChanges();
    }
}

This is a method that is in my Project class.

However, after querying my database, I find that it, in fact, did not update. I get no errors or exceptions from this. When I step through, I can see the changes to the project that I made.

Upvotes: 1

Views: 99

Answers (2)

Kami
Kami

Reputation: 19457

You must make changes to the entity after it is attached.

For example

context.Projects.Attach(project);

project.Name = "New Funky Name";

context.SaveChanges();

If the entity is being modified outside you save/update method as per your example, then you may need to flag the state manually.

context.Projects.Attach(project);
DbEntityEntry entry = context.Entry(day);       // Gets the entity Entry instance
entry.Property("Name").IsModified = true;       // Individual property modified
entry.State = System.Data.EntityState.Modified; // or Entire object modified

Upvotes: 2

Saad Alothman
Saad Alothman

Reputation: 363

you need to tell Entity frame work that the state of the object that you have just attached have been changed in comparison with the value that is in the database, you simply modify the state of the entry as the following:

            db.Favorites.Attach(favorite);
            var ent = db.Entry(favorite);
            ent.State = EntityState.Modified;   
            db.SaveChanges();

Have ago at it and let me know

Upvotes: 2

Related Questions