实体框架C#中的反射 [英] Reflection in Entity Framework C#

查看:148
本文介绍了实体框架C#中的反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用反射通过Entity Framework进行动态选择。

I am trying to use reflection to make a dynamic select through Entity Framework.

想法是该方法将获得列名(即参数值)作为参数每个要搜索的列以及每个列的顺序。

The idea is that the method will get as parameters the column name, the value for each column to search and the order of each column.

例如:

 public anEntity list(String ColumnName, String Value, String Order)
 {
    //
    //...
    items = (from r in context.Products
             where r.GetType().GetProperty(ColumnName). Contains(Value)))
             select r).OrderBy(Order).ToList();
    returns Items
 }

有可能吗?您能帮我吗?

Is it possible? Could you help me?

推荐答案

我有同样的事情!花了3个小时,找到了解决方案!

I had the same thing! Spent 3 hours and found the solution!

Expression.Lambda and query generation at runtime, simplest "Where" example

与EF,Expression>和LinqKit一起使用非常好。

It's very good work with EF, and Expression>, and LinqKit.

更改使用动态类型的代码:

Change code, for using dynamic types:

private Expression<Func<Goods, bool>> LambdaConstructor (string propertyName, string inputText, Condition condition)
    {

            var item = Expression.Parameter(typeof(Goods), "item");
            var prop = Expression.Property(item, propertyName);
            var propertyInfo = typeof(Goods).GetProperty(propertyName);
            var value = Expression.Constant(Convert.ChangeType(inputText, propertyInfo.PropertyType));
            BinaryExpression equal;
            switch (condition)
            {
                case Condition.eq:
                    equal = Expression.Equal(prop, value);
                    break;
                case Condition.gt:
                    equal = Expression.GreaterThan(prop, value);
                    break;
                case Condition.gte:
                    equal = Expression.GreaterThanOrEqual(prop, value);
                    break;
                case Condition.lt:
                    equal = Expression.LessThan(prop, value);
                    break;
                case Condition.lte:
                    equal = Expression.LessThanOrEqual(prop, value);
                    break;
                default:
                    equal = Expression.Equal(prop, value);
                    break;
            }
            var lambda = Expression.Lambda<Func<Goods, bool>>(equal, item);
            return lambda;
        }

对于OrderBy,请使用:
无法使用LINQ OrderBy中的属性名称进行排序

And for OrderBy using: Unable to sort with property name in LINQ OrderBy

这篇关于实体框架C#中的反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆