Note that there are some explanatory texts on larger screens.

plurals
  1. POPartially updating object with EF Code First and ASP.NET MVC
    primarykey
    data
    text
    <p>EF4.1-Code-First-Gurus!</p> <p>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:</p> <pre><code>public class Entity { [Key] public int Id { get; set; } [ScaffoldColumn(false)] public DateTime CreatedOn { get; set; } [ScaffoldColumn(false)] public DateTime ModifiedOn { get; set; } } </code></pre> <p>and </p> <pre><code>public class Person : Entity { public string FirstName { get; set; } public string LastName { get; set; } public DateTime Birthday { get; set; } } </code></pre> <p>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.</p> <p>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):</p> <pre><code> public void Update(Person person, List&lt;string&gt; properties) { Person tmpPerson = context.People.Single(x =&gt; 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; } </code></pre> <p>Now the controller is calling this method like this:</p> <pre><code> [HttpPost] public ActionResult Edit(Person person) { if (ModelState.IsValid) { personRepository.Update(person, new List&lt;string&gt; { "FirstName", "LastName", "Birthday"}); personRepository.Save(); return RedirectToAction("Index"); } else { return View(); } } </code></pre> <p>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).</p> <p>Maybe this is a similar question: <a href="https://stackoverflow.com/questions/4667621/how-to-update-ef-4-entity-in-asp-net-mvc-3">How To Update EF 4 Entity In ASP.NET MVC 3?</a></p> <p>I highly appreciate your help! Joris</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload