【问题标题】:Partially updating object with EF Code First and ASP.NET MVC使用 EF Code First 和 ASP.NET MVC 部分更新对象
【发布时间】:2011-05-02 20:28:32
【问题描述】:

EF4.1-Code-First-Gurus!

我想知道是否有更优雅的方式来处理以下 ASP.NET MVC 3 EF 4.1 Code First 场景:假设我们有以下 POCO:

public class Entity
{
    [Key]
    public int Id { get; set; }

    [ScaffoldColumn(false)]
    public DateTime CreatedOn { get; set; }

    [ScaffoldColumn(false)]
    public DateTime ModifiedOn { get; set; }
}

public class Person : Entity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
}

假设我们创建了一些标准的编辑视图,它们不包括 CreatedOn/ModifiedOn 字段,因为它们将在存储库中设置,而不是由用户设置。

在我的存储库中,我有以下更新方法。这些方法除了应更新的字段列表(不包括 CreatedOn/ModifiedOn 字段):

    public void Update(Person person, List<string> properties)
    {
        Person tmpPerson = context.People.Single(x => 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;
    }

现在控制器像这样调用这个方法:

    [HttpPost]
    public ActionResult Edit(Person person)
    {
        if (ModelState.IsValid) {

            personRepository.Update(person, new List<string> { "FirstName", "LastName", "Birthday"});

            personRepository.Save();
            return RedirectToAction("Index");
        } else {
            return View();
        }
    }

这一切都像一个魅力。但是,我真的不喜欢我必须手动指定字段。你将如何处理这个要求?当然,我可以将 CreatedOn/ModifiedOn 字段作为隐藏字段添加到视图中,但我不想将表单加载太多(还有更多字段)。

也许这是一个类似的问题: How To Update EF 4 Entity In ASP.NET MVC 3?

非常感谢您的帮助! 乔里斯

【问题讨论】:

    标签: asp.net-mvc ef-code-first entity-framework-4.1


    【解决方案1】:

    是的,还有更优雅的版本:

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

    你会这样调用方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多