实体框架6.1更新记录的子集 [英] Entity Framework 6.1 Updating a Subset of a Record

查看:199
本文介绍了实体框架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.

在我的研究,我发现回答这似乎是。适合我的需要,但是,尽管我尽了最大努力,我不能得到的代码按预期方式工作。

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



我在做什么错了?

What am I doing wrong?

推荐答案

您立足岗位工作的 http://stackoverflow.com/a/15339512/2015959 时,但在其他线程的未更改的字段(和因此,不在所附模型)均不是强制性的,并且这就是为什么它的工作。由于需要的领域,你会得到这样的验证错误

You based your work on the post http://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更新记录的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆