【问题标题】:Dynamic creation of an expression query for getting data from Entity Framework动态创建用于从实体框架获取数据的表达式查询
【发布时间】:2014-02-09 12:32:49
【问题描述】:

我想创建一个 Expression 类型的查询,它从 Entity Framework 获取实体的一些列。

假设我们有两个这样的类:

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Child MyChild { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我们有一个IQueryableParent 列表:

var q = new List<Parent>()
{
    new Parent {Id = 1, Name = "a", Number = 1, MyChild=new Child{Id=11,Name="Child_a",Number=2}},
    new Parent {Id = 2, Name = "b", Number = 1, MyChild=new Child{Id=22,Name="Child_b",Number=2}},
    new Parent {Id = 3, Name = "c", Number = 1, MyChild=new Child{Id=33,Name="Child_c",Number=2}},
}.AsQueryable();

我想获取用户确定的q 的那些属性的列表。例如,用户确定他需要Parent.NameParent.MyChils.Name。所以我应该给用户一个这样的匿名类型列表:

{"a","Child_a"}
{"b","Child_b"}
{"c","Child_c"} 

如果Parent 实体不包含任何外键属性(在此示例中为MyChild 属性),那么创建一个动态获取Parent 的某些属性的表达式属性非常容易。我有一个代码可以获取Person 的一些属性,而没有MyChild 属性:

var columns = new List<string> { "Id", "Name" };
var xParam = Expression.Parameter(typeof(Parent), "x");
var sourceProperties = columns.ToDictionary(name => name,
    name => q.ElementType.GetProperty(name));
var dynamicType = LinqRuntimeTypeBuilder.GetDynamicType(sourceProperties.Values);
var bindings =
    dynamicType.GetFields()
        .Select(p => Expression.Bind(p, Expression.Property(xParam, sourceProperties[p.Name])))
        .OfType<MemberBinding>();
var newExpr = Expression.New(dynamicType.GetConstructor(Type.EmptyTypes));
Expression selector = Expression.Lambda(Expression.MemberInit(
    Expression.New(dynamicType.GetConstructor(Type.EmptyTypes)), bindings), xParam);
var body = Expression.MemberInit(newExpr, bindings);
var lambda = Expression.Lambda<Func<Parent, dynamic>>(body, xParam);
var t = q.Select(lambda);

(这里有2个使用的方法:)

public static Type GetDynamicType2(Dictionary<string, Type> fields)
{
    if (null == fields)
        throw new ArgumentNullException("fields");
    if (0 == fields.Count)
        throw new ArgumentOutOfRangeException("fields", "fields must have at least 1 field definition");
    try
    {
        Monitor.Enter(builtTypes);
        string className = "MyDynamicType";
        if (builtTypes.ContainsKey(className))
            return builtTypes[className];
        TypeBuilder typeBuilder = moduleBuilder.DefineType(className,
            TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable);
        foreach (var field in fields)
            typeBuilder.DefineField(field.Key, field.Value, FieldAttributes.Public);
        builtTypes[className] = typeBuilder.CreateType();
        return builtTypes[className];
    }
    catch (Exception ex)
    {
    }
    finally
    {
        Monitor.Exit(builtTypes);
    }

    return null;
}

public static Type GetDynamicType(IEnumerable<PropertyInfo> fields)
{
    return GetDynamicType(fields.ToDictionary(f => f.Name, f => f.PropertyType));
}

但我仍然无法获取 MyChild 的内部属性 Parent 的属性。

怎么做?

【问题讨论】:

    标签: c# expression iqueryable


    【解决方案1】:

    由于没有人回答我的问题,我尝试了许多不同的方法来解决它,结果问题利用Expression 的递归创建解决了。 对于Class 类型的每个属性(如问题中的MyChild),我们最常创建一个ExpressionExpressions的创建大多是这样递归的:

        private Expression BuildExpression(Expression parentExpression,
            Type parentPropertyType, string pathOfChildProperty)
        {
            string remainPathOfChild;
            var childPropertyName = 
                  GetFirstPropertyNameFromPathAndRemainPath(pathOfChildProperty, out remainPathOfChild);
            if (string.IsNullOrEmpty(childPropertyName)) return parentExpression;
            var childPropInfo = parentPropertyType.GetProperty(childPropertyName);
            var childExpression = Expression.Property(parentExpression, childPropInfo);
            return !string.IsNullOrEmpty(remainPathOfChild)
                ? BuildExpressionForInternalProperty(childExpression, childPropInfo.PropertyType, remainPathOfChild)
                : childExpression;
        }
        private string GetFirstPropertyNameFromPathAndRemainPath(string path, out string remainPath)
        {
            if (string.IsNullOrEmpty(path))
            {
                remainPath = null;
                return null;
            }
            var indexOfDot = path.IndexOf('.');
            if (indexOfDot < 0)
            {
                remainPath = null;
                return path;
            }
            remainPath = path.Substring(indexOfDot + 1);
            return path.Substring(0, indexOfDot);
        }
        }
    

    当内部属性的剩余路径为空时,递归调用将停止。 这个方法的最高级别调用是这样的:

    var inputParameter = Expression.Parameter(typeof(GrandParent), "x");
    var expChildProperty = 
        BuildExpression(inputParameter,typeof(Parent),"Parent.MyChils.Name");
    

    上述问题的最终结果表达式在调试视图中为(($x.Parent).MyChils).Name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多