c# - Entity Framework 6.1 更新记录的子集

标签 c# entity-framework entity-framework-6.1

我有一个 View 模型,它只封装了数据库模型属性的一些。 View 模型包含的这些属性是我想要更新的唯一属性。我希望其他属性保留它们的值(value)。

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

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

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 ,但在另一个线程中,未更改的字段(因此不在附加模型中)不是强制性的,这就是它起作用的原因。由于您的字段是必填项,因此您会收到此验证错误。

问题中提供的解决方案可以解决您的问题Entity Framework validation with partial updates

关于c# - Entity Framework 6.1 更新记录的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566781/

相关文章:

c# - 为什么 C# 使用不同的命名约定?

c# - 属性路由区别?

sql - Entity Framework 代码第一类,其父类和子类的类型与其自己的类相同

c# - 我可以在某些情况下关闭模拟吗

c# - Visual Studio 测试任务 : Test Assembly wildcard format

asp.net-mvc - ADO.NET 实体数据模型不更新实体

c# - Entity Framework 5.x 6.x 缓存框架

c# - EF 6.1 序列包含多个元素

ef-code-first - 如何更改 Entity Framework 6 中字符串属性的默认最大长度?

c# - Entity Framework 创建空迁移但坚持认为我的模型不同