The code you use to render the view and update the entity are quite relevant but missing, but I can guess what they look like:
@model ...rep
@using (Html.BeginForm()) {
@Html.HiddenFor(m => m.repid )
@Html.TextBoxFor(m => m.FirstName )
@Html.TextBoxFor(m => m.LastName)
<input type="submit" />
}
And in your controller:
[HttpPost]
public ActionResult Update(rep model)
{
using (var context = new MyContext())
{
context.reps.Attach(model);
context.SaveChanges();
}
return RTA(...);
}
This is attaching the entity that was posted, which is an entirely new object that is unknown to the context and its change tracker. By attaching an entity like that, you tell the context this is the new representation you want saved, i.e. with most properties set to null
.
You can easily fix this by first retrieving the entity and then updating only the required properties:
[HttpPost]
public ActionResult Update(rep model)
{
using (var context = new MyContext())
{
var entity = context.reps.Find(rep.repid);
entity.FirstName = model.FirstName;
entity.LastName = model.LastName;
context.SaveChanges();
}
return RTA(...);
}
But don't do this. See What is ViewModel in MVC? or ViewModel Best Practices or search the web or this site on "mvc viewmodel".
Mainly because your database entity contains columns you don't want displayed or updated (mass assignment) and because sooner or later you will want to use extra properties in your view (dropdown data, script variables, related entities) that you can't stick in your database entities.
Genarally you can say: don't use entity models for view models, especially not when they are posted back. So the viewmodel is the way to go:
public class RepresentativeViewModel
{
public string RepID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
You then only have to alter your view's model declaration:
@model ...RepresentativeViewModel
And your controller just looks like the easiest solution:
[HttpPost]
public ActionResult Update(RepresentativeViewModel model)
{
using (var context = new MyContext())
{
var entity = context.reps.Find(rep.RepID);
entity.FirstName = model.FirstName;
entity.LastName = model.LastName;
context.SaveChanges();
}
return RTA(...);
}
You can of course replace the entity.FirstName = model.FirstName;
mapping code into some automated solution, for example using AutoMapper.