EF4.1-Code-First-Gurus!
I wonder if there is a more elegant way to handle the following ASP.NET MVC 3 EF 4.1 Code First script: Let's say we have the following POCOs:
public class Entity { [Key] public int Id { get; set; } [ScaffoldColumn(false)] public DateTime CreatedOn { get; set; } [ScaffoldColumn(false)] public DateTime ModifiedOn { get; set; } }
and
public class Person : Entity { public string FirstName { get; set; } public string LastName { get; set; } public DateTime Birthday { get; set; } }
Suppose we have created some standard types of editing that do not include the CreateOn / ModifiedOn fields, since they will be installed in the repository, and not by the user.
In my repository, I have the following update method. Methods exclude the list of fields that need to be updated (leaving the CreateOn / ModifiedOn fields selected):
public void Update(Person person, List<string> properties) { Person tmpPerson = context.People.Single(x => x.Id == person.Id); context.People.Attach(tmpPerson); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(person)) { if (properties.Contains(descriptor.Name)) descriptor.SetValue(tmpPerson, descriptor.GetValue(person)); } tmpPerson.ModifiedOn = DateTime.Now; }
The controller now calls this method as follows:
[HttpPost] public ActionResult Edit(Person person) { if (ModelState.IsValid) { personRepository.Update(person, new List<string> { "FirstName", "LastName", "Birthday"}); personRepository.Save(); return RedirectToAction("Index"); } else { return View(); } }
It all works like a charm. However, I really do not like that I have to specify the fields manually. How would you handle this requirement? Of course, I could add CreateOn / ModifiedOn fields as hidden fields to the view, but I donβt want to unload the form by many (there are much more fields).
Perhaps this is a similar question: How to update an EF 4 object in ASP.NET MVC 3?
I appreciate your help! Joris
Net User HH
source share