2011-04-05 57 views
1

參考this post,不幸的是我又遇到了一些問題。在現實中,並不是所有的實體都包含相同的共同屬性,但是我需要繼承/實現我的接口,因此,在某個人的情況下,這些屬性只是聲明性的,否則就是其他情況。EF - 常見查詢

問題就在這裏:

public static IQueryable<T> Create<T>(ObjectContext context) 
    where T : class, IEntity 
{   
    var query = context.CreateObjectSet<T>().AsQueryable();   
    return query.Where(x => x.CommonProperties == "some value"); // problem here!!  
} 

事實上,如果沒有我的實體(文件)的包含公共屬性或其他任何人,最終查詢不會可瀏覽並會生成異常。

我試着用下面的代碼沒有成功:

System.Reflection.PropertyInfo p = query.ElementType.GetProperty("common1"); 
if (p != null) query = query.Where(x => x.common1 == "value.."); // problem here!! 

在這種情況下,p變量從未null,所以我的查詢destinated失敗..

幫我請..

+0

呵呵,你這個可憐的傢伙,究竟是誰強迫你寫共同的查詢代碼來處理沒有共同點的東西?那麼,如果你真的必須,在這個問題上看看Bennor McCarthy的壯觀答案:http://stackoverflow.com/questions/4782001/how-to-include-an-and-expression-that-c​​hecks-for -a-property-and-its-value它並沒有涵蓋完全相同的問題,而是非常類似的問題,所以也許你需要在答案中稍微調整沉重的反射代碼片段。但這是一個起點。祝你好運! – Slauma 2011-04-05 16:46:59

+0

@Slauma:它開始幾天前http://stackoverflow.com/questions/5496713/entity-wrapper-custom ...仍然是同樣的問題,仍然是一樣的強硬。 – 2011-04-05 17:38:11

回答

1
ParameterExpression itemParameter = Expression.Parameter(typeof(T)); 
return query.Where(Expresion.Equal(Expression.Property(itemParameter, "COMMONPROP_NAME"), Expression.Constant("VALUE")));