实体框架 6.1 更新记录的子集

Entity Framework 6.1 Updating a Subset of a Record(实体框架 6.1 更新记录的子集)

本文介绍了实体框架 6.1 更新记录的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仅封装一些数据库模型属性的视图模型.视图模型包含的这些属性是我要更新的唯一属性.我希望其他属性保持其价值.

I have a view model that encapsulates only some of the database model properties. These properties contained by the view model are the only properties I want to update. I want the other properties to preserve their value.

在研究过程中,我发现 this 答案似乎非常适合我的需求,但是,尽管我尽了最大努力,我无法让代码按预期工作.

During my research I found this answer which appears to be perfect for my needs however, despite my best efforts, I cannot get the code to work as expected.

这是我想出的一个孤立的例子:

Here is an isolated example of what I came up with:

static void Main() {
    // Person with ID 1 already exists in database.

    // 1. Update the Age and Name.
    Person person = new Person();
    person.Id = 1;
    person.Age = 18;
    person.Name = "Alex";

    // 2. Do not update the NI. I want to preserve that value.
    // person.NINumber = "123456";

    Update(person);
}

static void Update(Person updatedPerson) {
    var context = new PersonContext();

    context.Persons.Attach(updatedPerson);
    var entry = context.Entry(updatedPerson);

    entry.Property(e => e.Name).IsModified = true;
    entry.Property(e => e.Age).IsModified = true;

    // Boom! Throws a validation exception saying that the 
    // NI field is required.
    context.SaveChanges();
}

public class PersonContext : DbContext {
    public DbSet<Person> Persons { get; set; }
}

public class Person {
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required] 
    public int Age { get; set; } // this is contrived so, yeah.
    [Required]
    public string NINumber { get; set; }
}

我做错了什么?

推荐答案

您的工作基于帖子 https://stackoverflow.com/a/15339512/2015959,但在另一个线程中,未更改的字段(因此不在附加模型中)不是强制性的,这就是它起作用的原因.由于您的字段是必需的,因此您会收到此验证错误.

You based your work on the post https://stackoverflow.com/a/15339512/2015959, but in the other thread the fields that weren't changed (and as such weren't in the attached model) weren't mandatory, and that's why it worked. Since your fields are required, you'll get this validation error.

您的问题可以通过问题中提供的解决方案来解决带有部分更新的实体框架验证

Your problem can be solved by the solution provided in question Entity Framework validation with partial updates

这篇关于实体框架 6.1 更新记录的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:实体框架 6.1 更新记录的子集

基础教程推荐