问题描述
是否有可能在调用 SaveChanges
之前验证已经添加到上下文中的实体,并删除无效的实体,这样我就不会得到 EntityValidationErrors
是否保存?
Is it possible to validate entities that I've already added to the context before I call SaveChanges
and remove the invalid ones so that I don't get the EntityValidationErrors
on save?
我有大约3k个实体的列表,其中一些包含无效数据,这些数据会阻止所有其他实体被保存。我不想单独保存每个实体,而忽略那些有错误的实体。
I have a list of about 3k entities and some of them contain invalid data that prevent all other entities to be saved. I wouldn't like to save each entity separately but rather ignore those that have errors.
试图找到解决方案,我发现您可以禁用验证。如果我这样做了, SaveChanges
会忽略无效的变量并保存其他变量吗?
Trying to find a solution to this I found that you can disable the validation. If I did it, would SaveChanges
ignore the invalid ones and save the others?
Context.Configuration.ValidateOnSaveEnabled = false;
但是我更喜欢调用某种方法来调用实体验证并将其从上下文中删除。或者,也许甚至可以在将实体添加到上下文之前对其进行验证?
I would however prefer to call some method to invoke entity validation and remove it from the context. Or maybe it's even possible to validate an entity before I add it to the context? This would be even better.
推荐答案
直接解决方案是在保存之前验证它们,并分离出带有错误的实体。
The direct solution is validating them before save, and detach those entities with errors.
foreach (var error in dbContext.GetValidationErrors())
{
dbContext.Entry(error.Entry).State = EntityState.Detached;
}
但这更像是一种解决方法。 IMO,您应该更早地避免验证错误(例如,在api层),而不是避免在数据层中保存。
But it's more like a workaround. IMO you should avoid the validation errors more earlier (e.g. in the api layer), instead of preventing from saving in the data layer.
这篇关于在从上下文保存和删除之前验证实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!