2009-09-11 85 views
0

我希望能夠將變量類型傳遞給方法,主要是爲了將實體框架查詢傳遞給將應用常見包含嵌套對象的方法。將變量類型傳遞給未枚舉的方法

這就是我想做的事......

public Person GetPersonByID(int personID) 
{ 
    var query = from Perspn p in Context.Persons 
       where p.PersonID = personID 
       select p; 

    ObjectQuery<Person> personQuery = ApplyCommonIncludes<Person>(query); 

    return personQuery.FirstOrDefault(); 
} 


public ObjectQuery<T> ApplyCommonIncludes<T>(SomeType query) 
{ 
    return ((ObjectQuery<T>)query) 
      .Include("Orders") 
      .Include("LoginHistory"); 
} 

回答

0

我最終創建了一種不同的方法。我的存儲庫現在有一個用於包含的字符串列表。爲了保持類型安全創建包括,我創建了以下類:

/// <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,將應用包含,執行查詢並返回結果。不是我想要的,但運作良好。

3

好像是你真正想要SomeTypeObjectQuery<T>,對不對?

public ObjectQuery<T> ApplyCommonIncludes<T>(ObjectQuery<T> query) 
{ 
    return query 
      .Include("Orders") 
      .Include("LoginHistory"); 
} 

這是有效的語法。這有什麼問題嗎?

這應該工作,並延遲執行(我認爲這是你的意思是「沒有枚舉」),直到調用FirstOrDefault()。