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

Cas*_*roy 15 c# entity-framework entity-framework-6.1

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

在我的研究过程中,我发现这个 答案看起来很适合我的需求,但是,尽管我付出了最大的努力,但我无法让代码按预期工作.

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

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; }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Rad*_*cal 4

您的工作基于帖子/sf/answers/1073765871/,但在另一个线程中,未更改的字段(因此不在附加模型中)不是强制性的,这就是它起作用的原因。由于您的字段是必填字段,因此您将收到此验证错误。

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