POIR
POIR

Reputation: 3190

MVC Entity Framework Update

In attached photo you can see my database diagram. Everytime I make an update on post I want to delete all PostMappings. I tried with the following code:

 public ActionResult Edit(Post post, string[] selectedCategories)
    {


        if (ModelState.IsValid)
        {

            post.PostMappings = new List<PostMapping>();

            db.Entry(post).State = EntityState.Modified;

            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(post);
    }

But, It didn't worked.

enter image description here

Upvotes: 0

Views: 50

Answers (1)

Brian Driscoll
Brian Driscoll

Reputation: 19635

It's not working because you're not actually changing the state of the existing PostMappings. If you want to explicitly delete them, then you'll need to iterate over the collection and set the state of each one, e.g.:

foreach (var mapping in post.PostMappings)
{
    db.Entry(mapping).State = EntityState.Deleted;
}

If an entity has a navigation item and it is unset when changes are saved, EF doesn't make any assumptions about what changes you want to happen in the database. It just assumes that the navigation item was never loaded (remember, navigation items are lazy loaded by default).

So, short of painting a really broad stroke by turning lazy loading off, you need to explicitly set state on loaded navigation items.

Upvotes: 1

Related Questions