如何在没有扩展方法的变量中按名称存储实体属性?

时间:2017-10-16 02:07:20

标签: c# entity-framework

我已经放弃尝试解释这两个问题之间的区别,并试图删除这个问题,但系统不会让我。对不起,我浪费了大家的时间。

但是这两个问题之间肯定存在差异,每个问题都是单独解决的:

Entity.OrderBy("field name")  //<-- Extension method

Expression<Func<TE,TK>> myvar; 
Entity.OrderBy( myvar)        //<-- Variable holding an Expression

我正在尝试创建一个函数,将字符串名称转换为引用实体属性而不使用扩展方法的Lambda表达式。我们使用的存储库接受Lambdas,因此我们无法发送它扩展方法。

// LinqPad for testing
void Main()
{
    string prop = "sku";

    // We can store data type of property in variable, but how
    // do we convey that value in the <> brackets?
    Expression<Func<[Entity type],[Property type]>> orderby;

    orderby = Me.GetOrder<Product,[How do I get SKU type here?]>("sku");

    Product.OrderBy( orderby).Skip(10).Take(10).Dump();

}

public static class Me
{
    public static Expression<Func<TE, TK>> GetOrder<TE,TK>(
        string propertyName) where TE: class
    {
        //Create x=>x.PropName
        var propertyInfo = typeof(TE).GetProperty(propertyName);
        ParameterExpression arg = Expression.Parameter(typeof(TE), "x");
        MemberExpression property = Expression.Property(arg, propertyName);
        var selector = Expression.Lambda<Func<TE,Object>>(property, 
                                  new ParameterExpression[] { arg });

        return selector;
    }
}

1 个答案:

答案 0 :(得分:-1)

这样的事情怎么样?

    private static Dictionary<string, Func<Product,IComparable>> lookup= new 
  Dictionary<string, Func<Product,IComparable>>() { { "S", NewMethod}, { "D", NewMethodD}};


            private static IComparable NewMethod(Product a)
            {
                return a.SKU;
            }
            private static IComparable NewMethodD(Product a)
            {
                return  a.OtherTHing;
            }

然后您可以.OrderBy(lookup["S"]).OrderBy(lookup["D"])

与您的相似,但将其与您可以存储的内容(密钥)相关联。