I'm trying to use Entity Framework in an ASP.NET MVC web application.

Let's say I have an Entity "people", with some anagraphical details.

My web application has a view where, using Ajax, I can change my details one by one.

For example, I can change only the "name" of my entity, using an Ajax post.

What's the best practice to implement a method in my controller to perform this update on my "people" entity? I would like to create a general "update" method, not a specific method for each single property.

Thanks for helping me

share|improve this question
What do you mean by general update ? – Jayantha Oct 6 '11 at 11:27
I mean a function that can update different properties. I don't want to write a method for each single property of my entity. – Andrea R. Oct 7 '11 at 16:08
feedback

2 Answers

up vote 0 down vote accepted
public ActionResult Update(int id, string propertyName, object propertyValue)
{
    using(var ctx = new Db())
    {
       var person = ctx.People.First(n => n.Id == id);
       Type t = person.GetType();
       PropertyInfo prop = t.GetProperty(propertyName);
       prop.SetValue(person, propertyValue, null);
       ctx.SaveChanges();
    }
    return Json(new { Success = true });
}
share|improve this answer
Thanks, that's the code I was looking for. – Andrea R. Oct 7 '11 at 16:15
feedback

Why would you want to do that? Just pass the whole Entity and update it, it's in your view model anyways.

        [HttpPost]
        public ActionResult Edit(People people)
        {
            if (ModelState.IsValid)
            {
                db.Entry(people).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(people);
        }
share|improve this answer
Yes, that's the usual way to update an entity. But imagine you have a GUI where you can update just some properties (for example from the result of a search), and you don't have all the properties in your view. – Andrea R. Oct 7 '11 at 16:12
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.