乍一看,反应是:创建一个接口
public interface ObjectWithDepartmentInterface {
int depID;
}
使所有使用此 depId 的实体实现此接口,并使用
where T : ObjectWithDepartmentInterface
但是 linq to entity 不接受查询中接口的属性...参见例如:基于接口生成的表达式
因此,唯一的方法是使您的实体具有从具有 depId 属性的公共实体(可能是抽象的)继承的 depId。
并使用这个抽象实体作为
where T:
一种更简单(但更丑陋的方法)可能是不对 T 添加约束,在方法中构建谓词,并在坏情况下抛出异常。
if (typeof(T).GetProperty("depId") == null)
throw InvalidOperationException (string.Format("{0}" doesn't have a depId property, typeof(T).Name))
编辑
但也许不是 depId 作为公共属性的问题 那么
public static IQueryable<T> WhereExistsOrAll<T>(this IQueryable<T> source, string propertyName, int value)
where T: // is what?
{
if (value == 0)
return source;
var parameter = Expression.Parameter(typeof(T), "m");
Expression member = parameter;
member = Expression.Property(member, propertyName);
member = Expression.Equals(member, Expression.Constant(value));
var lambda = Expression.Lambda<Func<T, bool>>(member, new[]{parameter});
return source.Where(lambda);
}
用法
var stRecs = db.<someTable>.WhereExistsOrAll("depId", depId);
编辑 2
另一种方法是解析谓词以获得“常量”值
类似的东西
public static IQueryable<T> GetAllOrRestrict<T>(this IQueryable<T> queryable, Expression<Func<T, bool>> predicate)
{
var expression = predicate.Body as BinaryExpression;
var rightPart = expression.Right as MemberExpression;
var value = GetValue(rightPart);
var test = value.ToString();
int val;
if (Int32.TryParse(value.ToString(), out val))
{
if (val != 0)
return queryable.Where(predicate);
}
return queryable;
}
private static object GetValue(MemberExpression member)
{
var objectMember = Expression.Convert(member, typeof(object));
var getterLambda = Expression.Lambda<Func<object>>(objectMember);
var getter = getterLambda.Compile();
return getter();
}
用法
var stRecs = db.<someTable>.GetAllOrRestrict(m => m.depID == depId);