2015-09-02 37 views
1

我使用LinqKIT的.AsExpandable()擴展來動態生成Where表達式。如何在使用LinqKIT的.AsExpandable()時包含子實體(導航)

例如,

Expression<Func<Asset, bool>> assetNamePredicate = m => m.AssetName == "abc"; 
Expression<Func<Asset, bool>> assetPurchaseDateFromPredicate = m => m.PurchaseDate > DateTime.Now.AddDays(-10); 
Expression<Func<Asset, bool>> whereExpression = t => assetNamePredicate.Invoke(t) && assetPurchaseDateFromPredicate.Invoke(t); 

return new entitiesContainer().Set<Asset>().AsExpandable().Where(whereExpression).ToList<Asset>(); 

現在資產實體包含其具有外鍵AssetType表中的ID字段AssetTypeID。 但是,當我嘗試編寫Include語句以將AssetType包含在結果集中時,它不起作用,並且每個Asset實體的AssetType屬性始終爲空...但是,如果我不使用.ExExpandable()擴展。

任何有關我們如何使用AsExpandable()擴展結果集來加載相關實體的想法。

P.S. - 我的場景比我提供的示例代碼有點複雜,所以我無法避免使用此擴展名。

回答

0

我發現解決這個問題 - 基本上,這需要創造的「包含」表達一個數組,查詢對他們 -

例如,

List<Expression<Func<Asset, object>>> includes = new List<Expression<Func<Asset, object>>>(); 
    includes.Add(m => m.City); 
    includes.Add(m => m.City.Country); 

     return includes 
      .Aggregate(query.AsQueryable(), (current, include) => current.Include(include)) 
      .AsExpandable() 
      .Where(whereExpression) 
      .ToList<Address>(); 
0

顯然,AsExpandable擴展方法返回不同的返回類型是一個已知問題,因此打破了包含實體框架的一點。有一個解決方法:預測。如果您定義了一個Select語句,您可以在其中導航到您的導航屬性,那麼您應該能夠將它們包含在結果集中。

相關問題