2015-05-04 114 views
-2

我有一个DataClassesDataContext包含一组表,我试图做lambda expression动态过滤使用只有表的名称和字段的名称。基本上我想为每个表找到一个具有特定ID的行是否已经存在。SingleOr的动态lambda表达式默认

如果我知道时间提前的表,我会用:

if (dataClassesDataContext.MYTABLEXs.SingleOrDefault(m => m.MYTABLEX_ID == MyId)) 
    DoExists(); 

但正如我得到的表名MYTABLEX和MYTABLEY(和字段名MYTABLEX_ID和MYTABLEY_ID)作为对飞弦,我试图在运行时构建上述过滤器。

我可以访问使用动态表:

Type tableType = Type.GetType(incommingtableName); // incommingtableName being looped over MYTABLEX, MYTABLEY , ... 
var dbTable = dataClassesDataContext.GetTable(tableType); 

但后来我卡住了。我如何建立一个表达如下的lambda表达式:

if (dbTable.SingleOrDefault(m => m.incommingtableName_id == MyId)) 
    DoExists(); 

任何想法?

+0

您可以用[表达式](HTTPS构建它们: //msdn.microsoft.com/en-us/library/system.linq.expressions.expression%28v=vs.110%29.aspx)类,允许您在运行时动态构建表达式 –

回答

1

您可以在运行时构建表达式。而且您还需要有通用版本的SingleOrDefault方法。下面是例子:

Type tableType = typeof (incommingtableName); // table type 
string idPropertyName = "ID"; // id property name 
int myId = 42; // value for searching 

// here we are building lambda expression dynamically. It will be like m => m.ID = 42; 
ParameterExpression param = Expression.Parameter(tableType, "m"); 
MemberExpression idProperty = Expression.PropertyOrField(param, idPropertyName); 
ConstantExpression constValue = Expression.Constant(myId); 

BinaryExpression body = Expression.Equal(idProperty, constValue); 

var lambda = Expression.Lambda(body, param); 


// then we would need to get generic method. As SingleOrDefault is generic method, we are searching for it, 
// and then construct it based on tableType parameter 

// in my example i've used CodeFirst context, but it shouldn't matter 
SupplyDepot.DAL.SupplyDepotContext context = new SupplyDepotContext(); 
var dbTable = context.Set(tableType); 


// here we are getting SingleOrDefault<T>(Expression) method and making it as SingleOrDefault<tableType>(Expression) 
var genericSingleOrDefaultMethod = 
    typeof (Queryable).GetMethods().First(m => m.Name == "SingleOrDefault" && m.GetParameters().Length == 2); 
var specificSingleOrDefault = genericSingleOrDefaultMethod.MakeGenericMethod(tableType); 

// and finally we are exexuting it with constructed lambda 
var result = specificSingleOrDefault.Invoke(null, new object[] { dbTable, lambda }); 

至于可能的优化构建拉姆达可以被缓存,因此我们不会每次都需要构建它,但它应该工作一样

+0

感谢您的代码 – Yahia