我有一个 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/