Rya*_*n Z 11 c# linq entity-framework-6
我的问题是我需要查询泛型类中属性的值.该属性标有属性.
请参阅以下代码:
var rowKeyProperty = EFUtil.GetClassPropertyForRowKey<T>();
var tenantKeyProperty = EFUtil.GetClassPropertyForTenantKey<T>();
var queryResult =
objContext.CreateObjectSet<T>().Single(l => (((int) tenantKeyProperty.GetValue(l, null)) == tenantKey) &&
(((int)rowKeyProperty.GetValue(l, null)) == KeyValue));
Run Code Online (Sandbox Code Playgroud)
rowKeyProperty和tenantKeyProperty的类型为System.Reflection.PropertyInfo.
我理解为什么我收到错误.当linq查询转换为SQL时,它无法理解property.GetValue.
但是,我对这里的工作感到非常难过.有没有人有任何想法如何实现这一目标?谢谢.
Ser*_*rvy 19
您需要实际构建Expression对象以表示您希望它模仿的表达式,在这种情况下,您要表示的表达式是:
l => l.SomeProperty == SomeValue
Run Code Online (Sandbox Code Playgroud)
因此,您需要逐位构建该组件的每个组件,从创建参数,定义相等运算符,属性访问,常量值等.
public static Expression<Func<TItem, bool>> PropertyEquals<TItem, TValue>(
PropertyInfo property, TValue value)
{
var param = Expression.Parameter(typeof(TItem));
var body = Expression.Equal(Expression.Property(param, property),
Expression.Constant(value));
return Expression.Lambda<Func<TItem, bool>>(body, param);
}
Run Code Online (Sandbox Code Playgroud)
完成所有操作后,您可以使用您拥有的数据调用它:
var queryResult = objContext.CreateObjectSet<T>()
.Where(PropertyEquals<T, int>(tenantKeyProperty, tenantKey))
.Where(PropertyEquals<T, int>(rowKeyProperty, KeyValue))
.Single();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8077 次 |
| 最近记录: |