Entity Framewor 学习笔记 (include + where)
如果我们想在子查询做过滤的话应该怎样写呢?
IEnumerable<Product> products = db.products.Include(p => p.colors.Where(c => c.id == 5)).ToList();
product - color , 1-n
可能你以为是这样,但是结果是 error : "The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties."
正确的做法是使用一个匿名对象来包装
var products = db.products.Include(p => p.colors).Select(p => new { id = p.id, colors = p.colors.Where(c => c.id == 5) //还有其它属性 }).ToList();
这个方法虽然可以但是缺点很多,比如要写一堆属性=value, 而且出来是IEnumerable<匿名对象> 而不是 IEnumerable<Product>
所以呢我们应该要这样来写
IEnumerable<Product> products = db.products.Include(p => p.colors).Select(p => new { Product = p, colors = p.colors.Where(c => c.id == 5) //不需要其它属性了 }).ToList().Select(p => p.Product).ToList();
参考 : http://stackoverflow.com/questions/25276978/ef-6-add-where-clause-to-an-include-with-navigation-property
你可能有点疑惑,怎么这样写也行?!
其实原理很简单.
var product = db.products.ToList(); var colors = db.colors.ToList(); Color c = product.First().colors.First();
上面的第3句是可以拿到 color 的, 原理就是当 colors 被请求回来后,它会自动填入 product.colors 值,base on 他的 foreign key 做链接 。
只要在EF的作用域内,所有的关系都是会被填充的.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析