Andrea R.
Andrea R.

Reputation: 45

Update single property of an entity using Entity Framework and ASP.NET MVC

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

Upvotes: 3

Views: 1130

Answers (2)

epignosisx
epignosisx

Reputation: 6192

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

Upvotes: 3

Michael D. Irizarry
Michael D. Irizarry

Reputation: 6302

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

Upvotes: 2

Related Questions