我最終創建了一種不同的方法。我的存儲庫現在有一個用於包含的字符串列表。爲了保持類型安全創建包括,我創建了以下類:
/// <summary>
/// Builds Includes
/// </summary>
public class IncludeBuilder
{
/// <summary>
/// List of parts for the Include
/// </summary>
private List<string> Parts;
/// <summary>
/// Creates a new IncludeBuilder
/// </summary>
private IncludeBuilder()
{
this.Parts = new List<string>();
}
/// <summary>
/// Creates a new IncludeBuilder
/// </summary>
public static IncludeBuilder Create()
{
return new IncludeBuilder();
}
/// <summary>
/// Adds a property name to the builder
/// </summary>
public IncludeBuilder AddPart<TEntity, TProp>(Expression<Func<TEntity, TProp>> expression)
{
string propName = ExpressionHelper.GetPropertyNameFromExpression(expression);
this.Parts.Add(propName);
return this;
}
/// <summary>
/// Gets a value of the include parts separated by
/// a decimal
/// </summary>
public override string ToString()
{
return string.Join(".", this.Parts.ToArray());
}
這讓我做到這一點...
myPersonRepository.AppendInclude(
IncludeBuilder.Create()
.AddPart((Person p) => p.Orders)
.AddPart((Order o) => o.Items));
上述語句將表達式的IncludeBuilder類然後轉換以上轉化爲「Orders.Items」。
然後我在我的RepositoryBase中創建了一個輔助方法,該方法給定一個ObjectQuery,將應用包含,執行查詢並返回結果。不是我想要的,但運作良好。