国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Entity Framewor 學習筆記 (include + where)

2019-11-17 02:02:33
字體:
來源:轉載
供稿:網友

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的作用域內,所有的關系都是會被填充的.


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 太和县| 宣恩县| 东丽区| 鄂托克前旗| 万山特区| 且末县| 彭山县| 桑日县| 桑植县| 兴义市| 盱眙县| 崇信县| 恩平市| 丹凤县| 丰宁| 扎赉特旗| 平顶山市| 临夏市| 中宁县| 兴文县| 兴国县| 六安市| 昂仁县| 澄迈县| 松江区| 潮州市| 新宾| 广丰县| 伽师县| 九龙县| 泰来县| 祥云县| 昔阳县| 拉孜县| 白银市| 庐江县| 贵德县| 开平市| 奎屯市| 清流县| 楚雄市|