Partially updating object with EF Code First and ASP.NET MVC

前端 未结 1 528
深忆病人
深忆病人 2021-02-06 16:22

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:

相关标签:
1条回答
  • 2021-02-06 17:15

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题