Entity Framework插入数据报错:Validation failed for one or more entities
www.111cn.net 编辑:lanve 来源:转载
今天在处理Entity Framework插入数据库时,报错:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

一直我一直用Exception ex,这个通用异常处理,一点都差不多哪里出错了。对照实体model和数据库表也都没有一点问题(EF刚开始用,以前都是同事给写好了,我只做前端);
1、解决第一步:
但是,按照他的提示 “See 'EntityValidationErrors' property for more details.” 去 Exception 中查看,却只能看到

并不能看到具体的是那个属性为什么验证不通过,也许不少人都遇到这种情况。
这里给大家介绍一个Exception类,让我们能够轻松的知道具体的哪一个字段出了什么问题。
那就是 System.Data.Entity.Validation.DbEntityValidationException,相信代码都知道怎么写了,最简单的就是
try
{
// 写数据库
}
catch (DbEntityValidationException dbEx)
{
}
在 dbEx 里面中我们就可以看到

这样子我们就能看到 EntityValidationErrors 所有的 ValidationErrors 的详细信息了。
2、去除对插入数据库依赖实体的数据:
我的实体A中有一个 public List<Shop> ShopList { get; set; } 的属性。报错的地方就是说明这个Shop实体的属性都是null。插入的时候shoplist的数据我另作处理,不在这里使用。这样就在service方法中将这个属性设置为null,就不会验证了。
public tb_WeiXinCard AddCard(tb_WeiXinCard Card)
{
using (PathAnalysisContext da = new PathAnalysisContext())
{
string strSql = "";
//if (type == 1)
//{
// strSql = string.Format("delete from tb_shopcard WHERE AgentId = {0}", id);
//}
StringBuilder sb = new StringBuilder();
List<int> listint = new List<int>();
foreach (Shop sp in Card.ShopList)
{
listint.Add(sp.Id);
}
//Card.ShopList = null;
Card = da.tb_WeiXinCard.Add(Card);
da.SaveChanges();
foreach (int sp in listint)
{
sb.Append(string.Format("insert into tb_shopcard ([cardid] ,[shopid]) VALUES ({0} ,{1});", Card.id, sp));
}
strSql = sb.ToString();
da.Database.ExecuteSqlCommand(strSql);
return Card;
}
}
简单记录一下。。

浙公网安备 33010602011771号