我有一个视图模型,仅封装了数据库模型的部分属性。这些包含在视图模型中的属性是我想要更新的唯一属性。我希望其他属性保留它们的值。
在研究过程中,我找到了这个答案,看起来非常适合我的需求,但是,尽管我尽了最大努力,我无法使代码按照预期工作。
这里是一个孤立的例子:
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; }
}
我做错了什么?