我有兩個類:如何更正替換類型的表達式?
public class DalMembershipUser
{
public string UserName { get; set; }
//other members
}
public class MembershipUser
{
public string UserName { get; set; }
//other members
}
我有功能:
public IEnumerable<DalMembershipUser> GetMany(Expression<Func<DalMembershipUser, bool>> predicate)
{
//but here i can use only Func<MembershipUser, bool>
//so i made transformation
query = query.Where(ExpressionTransformer<DalMembershipUser,MembershipUser>.Tranform(predicate));
}
當前實現:
public static class ExpressionTransformer<TFrom, TTo>
{
public class Visitor : ExpressionVisitor
{
private ParameterExpression _targetParameterExpression;
public Visitor(ParameterExpression parameter)
{
_targetParameterExpression = parameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return _targetParameterExpression;
}
}
public static Expression<Func<TTo, bool>> Tranform(Expression<Func<TFrom, bool>> expression)
{
ParameterExpression parameter = Expression.Parameter(typeof(TTo), expression.Parameters[0].Name);
Expression body = expression.Body;
new Visitor(parameter).Visit(expression.Body);
return Expression.Lambda<Func<TTo, bool>>(body, parameter);
}
}
//某處:.GetMany(u => u.UserName == "username");
例外:房產「系統。字符串用戶名'未定義爲類型'Memb ershipUser'
at line:new Visitor(parameter).Visit(expression.Body);
第二個塊中的查詢定義在哪裏? –
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –
只是好奇。這一切的目的是什麼? – Kryptos