Hi Please help. me,
I have a MVC 3 application, this is the scenario
Model
Public Class Person
{
public string PersonID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string DateOfBirth { get; set; }
public string MobileNo { get; set; }
public string TelNo { get; set; }
public string JobID { get; set; }
[ForeignKey("JobID")]
public virtual Job job { get; set; }
}
Public Class Job
{
public string JobID { get; set; }
public string Position { get; set; }
public string OfficeName { get; set; }
}
View Model
Public Class ViewModelPersonInfo
{
public string PersonID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Position { get; set; }
public string OfficeName { get; set; }
}
First in the controller i make a query of the "Person" then pass all needed values to the "ViewModelPersonInfo" then send the ViewModel to the "View", then the View displays the ViewModel using "EditorFor" meaning the View is set to allow the user to edit the displayed values.
Then when the user press "Save" the ViewModel is pass back to the controller with the new values then one by one i have to get the value of each properties of the ViewModel then pass back to "Person" model then call "saveChanges".
if you look on the Sql Profiler, you would see the that all Fields related Person model is re-updated eventhough some field does not change at all.
I also do some experiment, on the Action Method inside the Controller where the Updating is done, i try to query the Person model again, then Place this code
ContextEntities db = new ContextEntities(); var status = db.Entry(queryPersonResult); status.CurrentValues.SetValues(PassedViewModel);
Then call SaveChanges, then and it does update ONLY the fields the has been changed. But the Problem here is that the Object which is passed to "status.CurrentValues.SetValues" must have the same Property Name to the Person model (ViewModel.PersonID ~ Person.PersonID) so that the Person model will see its counter part name from the Viewmodel and able to recornize as if the ViewModel is actually a copy of the Person Model and detect what has been change then save that field only.
So finaly my Question: base on the scenario stated above, i want to Save only the field that has been changed but the Fields Name will not be identical between the Model and the ViewModel. How?
Thanks