如果我們想在子查詢做過濾的話應該怎樣寫呢?
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的作用域內,所有的關系都是會被填充的.
新聞熱點
疑難解答