最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Entity Framework插入数据报错:Validation failed for one or more entities
时间:2015-04-05 编辑:简简单单 来源:一聚教程网
今天在处理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
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(); Listlistint = new List (); 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; } }
简单记录一下。。
-
上一个: c# 拼装datatable3种方法总结
-
下一个: C#方法传参数的四种类型总结
相关文章
- jqGrid翻页时数据选中丢失问题的解决办法 04-05
- fiddler post二进制数据的例子 06-23
- 去掉DataGrid的ViewState中的无用数据 01-19
- 感受DataGrid给数据操作带来的便利(3) 01-12
- 感受DataGrid给数据操作带来的便利(2) 01-12
- dataGrid 中添加数据 01-12