我有看起來像這樣的(僞碼)的對象模型:NHibernate的遲緩裝載嵌套集合與期貨,以避免N + 1問題
class Product {
public ISet<Product> Recommendations {get; set;}
public ISet<Product> Recommenders {get; set;}
public ISet<Image> Images {get; set; }
}
當我加載給定的產品和要顯示的圖像其建議,我遇到了N + 1問題。 (這些建議是延遲加載,然後循環調用每個人的.Images財產。)
Product -> Recommendations -> Images
我想要做的就是急切地加載圖形的這個特殊的一部分,但我想不出怎麼做。我可以加載的建議熱切,但不是他們的形象。這是我一直在努力,但似乎並沒有工作:
//get the IDs of the products that will be in the recommendations collection
var recommendedIDs = QueryOver.Of<Product>()
.Inner.JoinQueryOver<Product>(p => p.Recommenders)
.Where(r => r.Id == ID /*product we are currently loading*/)
.Select(p => p.Id);
//products that are in the recommendations collection should load their
//images eagerly
CurrentSession.QueryOver<Product>()
.Fetch(p => p.Images).Eager
.Where(Subqueries.WhereProperty<Product>(p => p.Id).In(recommendedIDs))
.Future<Product>();
//load the current product
return CurrentSession.QueryOver<Product>()
.Where(p => p.Id == ID);
使用QueryOver,什麼是實現這一目標的最佳方式是什麼?我不想急於加載圖像,只是在這種特殊情況下。
編輯:我已經改變了我的方法,雖然它不正是我腦子裏想的,它避免了N + 1點的問題。我現在使用兩個查詢,一個用於產品,另一個用於查詢推薦的圖片。產品查詢非常簡單;這裏是圖像查詢:
//get the recommended product IDs; these will be used in
//a subquery for the images
var recommendedIDs = QueryOver.Of<Product>()
.Inner.JoinQueryOver<Product>(p => p.Recommenders)
.Where(r => r.Id == RecommendingProductID)
.Select(p => p.Id);
//get the logo images for the recommended products and
//create a flattened object for the data
var recommendations = CurrentSession.QueryOver<Image>()
.Fetch(i => i.Product).Eager
/* filter the images down to only logos */
.Where(i => i.Kind == ImageKind.Logo)
.JoinQueryOver(i => i.Product)
/* filter the products down to only recommendations */
.Where(Subqueries.WhereProperty<Product>(p => p.Id).In(recommendedIDs))
.List().Select(i => new ProductRecommendation {
Description = i.Product.Description,
ID = i.Product.Id,
Name = i.Product.Name,
ThumbnailPath = i.ThumbnailFile
}).ToList();
return recommendations;
我一直在尋找'TransformUsing' for 2 hours now!非常感謝.. – 2014-01-11 04:07:41
沒問題!很高興我能幫上忙。 – 2014-01-14 16:20:17