运行时中的“选择”实体包括导航属性

时间:2019-04-13 16:49:07

标签: c# entity-framework-core

有一个代码,请在运行时选择实体

Repository.GetAll().Select(Projection<Handbook, HandbookViewModel>())

public Expression<Func<T, D>> Projection<T, D>()
    {
        var baseParameter = Expression.Parameter(typeof(T), "base");
        var resultParameter = Expression.Parameter(typeof(D), "result");

        var bindings = typeof(D).GetProperties().Select(x => x.Name)
            .Select(name => new KeyValuePair<System.Reflection.MemberInfo, MemberExpression>(Expression.Property(resultParameter, name).Member, Expression.Property(baseParameter, name)))
            .Select(member => Expression.Bind(member.Key, member.Value));

        return Expression.Lambda<Func<T, D>>(Expression.MemberInit(Expression.New(typeof(D)), bindings), baseParameter);
    }

是否可以从导航属性以一对一的关系获取数据,例如base.CreatedUser.Name?

1 个答案:

答案 0 :(得分:0)

var baseParameter = Expression.Parameter(typeof(T), "base");
        var resultParameter = Expression.Parameter(typeof(D), "result");

        var bindings = typeof(D).GetProperties().Select(x =>
                                                {
                                                    var attr = x.GetCustomAttribute<AtpPropertyInfoAttribute>();

                                                    var entityProperties = attr != null && !string.IsNullOrEmpty(attr.EntityProperty) ? attr.EntityProperty.Split('.') : new string[] { x.Name };

                                                    Expression entityProperty = Expression.Property(baseParameter, entityProperties[0]);
                                                    for (int i = 1; i < entityProperties.Length; i++)
                                                    {
                                                        entityProperty = Expression.Property(entityProperty, entityProperties[i]);
                                                    }
                                                    return Expression.Bind(Expression.Property(resultParameter, x.Name).Member, entityProperty);
                                                });

        return Expression.Lambda<Func<T, D>>(Expression.MemberInit(Expression.New(typeof(D)), bindings), baseParameter);