I have 2 projects - a class library containing an EDM Entity Framework model and a seperate ASP.NET MVC project.
I'm having problems with how your suppose to edit and save changes to an entity using MVC. In my controller I have:
public class UserController : Controller
{
public ActionResult Edit(int id)
{
var rep = new UserRepository();
var user = rep.GetById(id);
return View(user);
}
[HttpPost]
public ActionResult Edit(User user)
{
var rep = new UserRepository();
rep.Update(user);
return View(user);
}
}
My UserRepository
has an Update method like this:
public void Update(User user)
{
using (var context = new PDS_FMPEntities())
{
context.Users.Attach(testUser);
context.ObjectStateManager.ChangeObjectState(testUser, EntityState.Modified);
context.SaveChanges();
}
}
Now, when I click 'Save' on the edit user page, the parameter user
only contains two values populated: Id, and FirstName. I take it that is due to the fact that I'm only displaying those two properties in the view.
My question is this, if I'm updating the user's firstname, and then want to save it, what am I suppose to do about the other User
properties which were not shown on the view, since they now contain 0 or NULL values in the user
object?
I've been reading a lot about using stub entities, but I'm getting nowhere fast, in that none of the examples I've seen actually work. i.e. I keep getting EntityKey related exceptions.
Can someone point me to a good tutorial/example of how to update EF 4 entities using a repository class, called by an MVC front-end?
Update Objects in Entity Framework 4.0First retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then edit the properties of the Entity and finally call SaveChanges() on the context.
To update an entity with Entity Framework Core, this is the logical process: Create instance for DbContext class. Retrieve entity by key. Make changes on entity's properties.
Update the .edmx file when the Database changes In the Model Browser, right-click the . edmx file and select Update Model from Database. Expand the Tables, Views, and Stored Procedures nodes, and check the objects you want to add to the . edmx file.
Right-click anywhere on the design surface, and select Update Model from Database. In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish.
I would retrieve the user from the database and update that entity. EF can't just magically know which values are supposed to be modified and which aren't.
If you're concerned about concurrency issues you would need to store the timestamp in the view - usually as a hidden form value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With