·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> Entity Framewor 学习笔记 (include + where)

Entity Framewor 学习笔记 (include + where)

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

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的作用域内,所有的关系都是会被填充的.