Entity Framework 6.1 Updating a Subset of a Record(实体框架 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.
在研究过程中,我发现 this 答案似乎非常适合我的需求,但是,尽管我尽了最大努力,我无法让代码按预期工作.
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; }
}
我做错了什么?
推荐答案
您的工作基于帖子 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 更新记录的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架 6.1 更新记录的子集
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01