public abstract class TEntity<T> where T : class
{
public virtual T Persistent<TProperty>(T entity, Expression<Func<TProperty>> propertyExpression)
{
var type = typeof(T);
string tableName = type.Name;
string propertyName = propertyExpression.GetMemberInfo().Name;//报错
var value = propertyExpression.GetValue();//报错
var id = type.GetProperty("Id").GetValue(entity, null);
//string.Format("update {0} set {1}=:value where Id=:id", tableName, propertyName))
return entity; }
} 有人能解释一下上面一段代码吗?有两处报错。
{
public virtual T Persistent<TProperty>(T entity, Expression<Func<TProperty>> propertyExpression)
{
var type = typeof(T);
string tableName = type.Name;
string propertyName = propertyExpression.GetMemberInfo().Name;//报错
var value = propertyExpression.GetValue();//报错
var id = type.GetProperty("Id").GetValue(entity, null);
//string.Format("update {0} set {1}=:value where Id=:id", tableName, propertyName))
return entity; }
} 有人能解释一下上面一段代码吗?有两处报错。
var value = propertyExpression.GetValue();//报错
这个报错是和你 的 这个参数 Expression<Func<TProperty>> propertyExpression 有关..你确定你的 这个参数在实例的时候又这些方法属性什么的么?
Expression以表达式树的形式将强类型 lambda 表达式表示为数据结构。此类不能被继承。Func<TProperty> funcpro = propertyExpression.Compile();
TProperty sdf = funcpro();这样TProperty算是拿到了
意思就是一个表达式树
“以表达式树的形式将强类型 lambda 表达式表示为数据结构”可以用来做动态生成语句的事情,比如linq里面的根据属性字段生成动态条件查询,因为属性字段不固定,所以可以用这种方法。举例如下(部分借鉴):
//将对象所有属性以and方式连接,并根据组成的条件查询出对象
public IQueryable<TEntity> Findx<TEntity>(IQueryable<TEntity> query, TEntity condition) where TEntity : class
{
PropertyInfo[] properties = condition.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); ParameterExpression paramx = Expression.Parameter(typeof(TEntity), "c");//c
Expression filter1 = null;
Expression filter2 = null; foreach (var item in properties)
{
if (item.GetValue(condition, null) != null)
{ Expression rightx = Expression.Constant(item.GetValue(condition, null));//value
Expression leftx = Expression.Property(paramx, item.Name);//c.? if (filter1 == null)
{
filter1 = Expression.Equal(leftx, rightx);//c.?=value
}
else
{
filter2 = Expression.Equal(leftx, rightx);//c.?=value filter1 = Expression.And(filter1, filter2);
}
}
else
{
continue;
}
} Expression<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(filter1, paramx); return query.Where(pred);
}其实最终生成的是一个代理希望对你有所帮助
对,其实可以这样用
Func<TProperty> funcpro = propertyExpression.Compile();
TProperty sdf = funcpro();