【发布时间】:2013-02-05 20:37:31
【问题描述】:
我在 winforms 应用程序中实现 EF 5,并将上下文 (DBContext) 保存在表单的私有字段中。
我尝试添加一个实体,因为它有一些无效的属性,我得到一个 DBEntityValidationException。然后,我将这些属性设置为有效值并尝试再次添加它,我收到完全相同的 DBEntityValidationException。
我想知道我是否需要清除任何东西?这是代码。
private SystemEntities _context = new SystemEntities(); // class field
try
{
Customer customer = ... // set properties here
_context.Customers.Add(customer);
_context.SaveChanges();
}
catch (DBEntityValidationException ex)
{
// get exception even though properties are updated with valid values
}
我在更新实体时没有发现这个问题。非常感谢。
【问题讨论】:
-
我建议循环并 Debug.WriteLine() 验证错误并查看哪些属性无法验证。也许它是一个没有设置为身份的 id 字段?
-
1) 如果您知道什么是有效值,为什么您依赖异常而不是一开始就正确设置值? 2) 您可以通过调用 DbContext.GetValidationErrors() 以一种侵入性较小的方式来执行您想要的操作,而不是捕获验证异常。 3) 确保你真的解决了问题。
-
谢谢!正如我的回答中所解释的那样,您的 cmets 为我指明了正确的方向。
标签: c# winforms entity-framework