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

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

这是一个孤立的例子,我想到了: p>

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

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