How to update related objects in Entity Framework

I have an MVC project and using Entity Framework Code First and POCO objects for a database. For example:

public class ClassA { public int? Id {get; set;} public string Name { get; set;} public virtual ClassB B {get; set;} } public class ClassB { public int? Id {get;set;} public string Description {get;set;} } 

I have an ActionResult that creates or edits a model. The problem is that when I call this ActionResult to update the model, and model.B was changed, the relation is not stored in the database. When an ActionResult is called to create a new object, it works as expected. How to solve this?

 public ActionResult Save(ClassA model) { model.B = GetBFromDb(model.B.Id.Value); if(ModelState.IsValid) { if (id.HasValue) { context.Entry(model).State = System.Data.EntityState.Modified; } else { context.ClassAs.Add(model); } context.SaveChanges(); // redirect to index etc. } return View("EditForm", model); } 
+8
c # asp.net-mvc-3 entity-framework ef-code-first
source share
3 answers

I solved it by changing ClassA with a foreign key to ClassB and setting the value to BId :

 public class ClassA { public int? Id {get; set;} public string Name { get; set;} public int BId {get;set;} // foreign key to B public virtual ClassB B {get; set;} } 

Why does this foreign key property do the job instead of the generated EF foreign key?

+3
source share

You can't just call:

 context.Entry(model).State = System.Data.EntityState.Modified; 

The object must first be extracted from the context so that EF can begin to track it. Then you need to apply any changes to this object before calling context.SaveChanges() .

 var entity = context.ClassAs.Find(model.Id); // set properties you want to modify on entity entity.Name = model.Name; entity.ClassB = context.ClassBs.Find(model.ClassB.Id); // other changes to entity as required... context.SaveChanges(); 

In this way, EF tracks the entity and knows how to apply the update to it.

+2
source share

If you attach and then set state to a modified entity infrastructure, you will send all properties for updating. You do not need to take the otter approach here, as this leads to a whole separate load. If you do so, then it makes no sense to go through the model, just the identifier, and then you call TryUpdateModel to populate the properties from the form.

Personally, the addition modified here is a little cleaner, since it doesn’t require a full round trip to download the data.

http://geekswithblogs.net/michelotti/archive/2009/11/27/attaching-modified-entities-in-ef-4.aspx

0
source share

All Articles