Partially updating object with EF Code First and ASP.NET MVC
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 scenario: Lets 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; }
}
Lets assume we have created some standard editing views, which are not including CreatedOn/ModifiedOn fields, because, they will be set in the repository and not by the user.
In my repository I have the following Update method. The methods excepts a list of fields, which should be updated (leaving CreatedOn/ModifiedOn fields out):
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;
}
Now the controller is calling this method like this:
[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();
}
}
This all works like a charm. However, I really dislike, that I have to specify the fields manually. How would you handle this requirement? Of course I could add CreatedOn/ModifiedOn fields as hidden fields to the view, but I dont want to bload the form to much (There are much more fields).
Maybe this is a similar question: How To Update EF 4 Entity In ASP.NET MVC 3?
I highly appreciate your help! Joris
Yes there is more elegant version:
public void Update(Person person, params Expression<Func<Person,object>>[] properties)
{
context.People.Attach(person);
DbEntityEntry<Person> entry = context.Entry(person);
foreach (var property in properties)
{
entry.Property(property).IsModified = true;
}
person.ModifiedOn = DateTime.Now;
}
You will call the method this way:
[HttpPost]
public ActionResult Edit(Person person)
{
if (ModelState.IsValid)
{
personRepository.Update(person, p => p.FirstName,
p => p.LastName, p => p.Birthday);
personRepository.Save();
return RedirectToAction("Index");
}
else
{
return View(person);
}
}
链接地址: http://www.djcxy.com/p/25464.html
上一篇: 实体框架4 / POCO