国产探花免费观看_亚洲丰满少妇自慰呻吟_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的作用域內,所有的關系都是會被填充的.


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南丹县| 和田县| 云南省| 广德县| 松桃| 清远市| 白玉县| 新余市| 博罗县| 塔城市| 雷波县| 邹平县| 白河县| 宁国市| 六枝特区| 庄浪县| 乐都县| 准格尔旗| 宜阳县| 临湘市| 伊金霍洛旗| 丰县| 阿合奇县| 闻喜县| 彭泽县| 宁武县| 建水县| 寻乌县| 肥西县| 都匀市| 澎湖县| 西贡区| 景泰县| 温泉县| 赞皇县| 巴中市| 如东县| 武陟县| 彭阳县| 齐齐哈尔市| 松溪县|