我意识到在不先选择实体的情况下更新实体是一个常见问题,StackOverflow 上已经有许多解决方案,但是在阅读这些内容后我仍然遇到问题。
我正在使用以下代码来更新用户实体:
using (var context = GetContext())
{
var userEntity = new UserEntity() { ID = userUpdate.ID };
context.Users.Attach(userEntity);
context.Entry(userEntity).CurrentValues.SetValues(userUpdate);
context.SaveChanges();
}
然而,这会导致抛出 DbEntityValidationException
,因为我的用户实体有一些必需的属性,但这些属性不一定在更新的实体上设置。
有什么办法解决这个问题,还是只是删除所需属性的情况?
谢谢!
最佳答案
我在这里找到了答案:Entity Framework/MVC3: temporarily disable validation
通过暂时禁用验证,我可以绕过检查并插入任意数量的值,而无需首先检索所需的属性:
using (var context = GetContext())
{
var userEntity = new UserEntity() { ID = userUpdate.ID };
context.Users.Attach(userEntity);
context.Entry(userEntity).CurrentValues.SetValues(userUpdate);
// Disable entity validation
context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();
}
关于c# - 在 Entity Framework 中更新具有所需属性的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107859/