3

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

2
  • What do you mean by general update ? Commented Oct 6, 2011 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. Commented Oct 7, 2011 at 16:08

2 Answers 2

3
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 });
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);
        }

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.