code first 导航属性标记为Required 修改时误报必填

fifexue 2015-07-23 09:59:59
模型类的某导航属性标记为Required,在模型update的时候误报该导航属性必须要‘必填’(其实是有值的 必须要重新赋值一遍才行)。

Models.Customer model = csBll.Find(c);

model.ResponsibleName =XXX;

csBll.Update(model);//此方法内DbEntityValidationException捕获到异常为导航属性不能为空(其实此时【model.导航属性】有值)


为什么会这样呢??我只想修改ResponsibleName,不修改另一个导航属性。

导航属性的Required标记 我不太想去掉,有办法解决吗
...全文
185 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
fifexue 2015-07-23
  • 打赏
  • 举报
回复
引用 7 楼 xml111024 的回复:
大牛太多,心里没底。 只说我的测试结果,用MiniProfiler跟了一下SQL,Find不加载导航属性,Include后才加载了需要的导航属性。 用VS断点看的结果,我认为是延迟加载的效果。
经过一番测试 我很认同你说的,非常好,谢谢了
xml111024 2015-07-23
  • 打赏
  • 举报
回复
大牛太多,心里没底。 只说我的测试结果,用MiniProfiler跟了一下SQL,Find不加载导航属性,Include后才加载了需要的导航属性。 用VS断点看的结果,我认为是延迟加载的效果。
xml111024 2015-07-23
  • 打赏
  • 举报
回复
Include把导航属性下值一起取出来,然后Update的时候就不报空了。
fifexue 2015-07-23
  • 打赏
  • 举报
回复
引用 2 楼 xml111024 的回复:
别用Find了,使用Include把导航属性添加进来,用Where
我当前取到的model是包含导航属性的 全都有值
fifexue 2015-07-23
  • 打赏
  • 举报
回复
引用 1 楼 fifexue 的回复:
我的find是个方法,里边是这样实现的: public T Find(Expression<Func<T, bool>> whereLambda) { T _entity = nContext.Set<T>().FirstOrDefault<T>(whereLambda); return _entity; } 这没问题吧 不用include
fayxue 2015-07-23
  • 打赏
  • 举报
回复
You can omit the [Required] attribute here because EF will detect the relationship as required by convention (due to the non-nullable FK property). This works also with enabled validation. The behaviour is a bit confusing since EF doesn't send a change of the FK column to the database, so there is not really a constraint violation and the Update command executes fine. I guess that the validation just checks the state of the model in memory (invalid, because Address is null) and not the state the model would have in the database when SaveChanges did execute (valid, because FK is correctly set). http://www.28im.com/csharp/a1693211.html
xml111024 2015-07-23
  • 打赏
  • 举报
回复
别用Find了,使用Include把导航属性添加进来,用Where
fifexue 2015-07-23
  • 打赏
  • 举报
回复

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧