Selection in GroupBy query with NHibernate with dynamic anonymous object

…衆ロ難τιáo~ 提交于 2019-12-24 03:38:08

问题


My main objective is to create a dynamic group by and use it in NHibernate.

Consider this non dynamic example that works:

_repository.Collection<User>().GroupBy(u => new { u.Active }).Select(s => s.Key, Count = s.Count())

Now, I create a dynamic object to generate the new { u.Active } part dynamically:

    private Expression<Func<T, object>> CreateGrouping<T>(IEnumerable<string> by)
    {
        var dynamicTypeForGroup = GetDynamicTypeForGroup<T>(by);
        var sourceItem = Expression.Parameter(typeof(T));

        var bindings = dynamicTypeForGroup
            .GetFields()
            .Select(p => Expression.Bind(p, Expression.PropertyOrField(sourceItem, p.Name)))
            .Cast<MemberBinding>()
            .ToArray();
        return Expression.Lambda<Func<T, object>>(Expression.Convert(
            Expression.MemberInit(
                Expression.New(dynamicTypeForGroup.GetConstructor(Type.EmptyTypes)),
                bindings),
            dynamicTypeForGroup),
        sourceItem);
    }

The type is generated in method GetDynamicTypeForGroup and then instantiated with Expression.MemberInit(Expression.New(dynamicTypeForGroup.GetConstructor(Type.EmptyTypes)), bindings)

This is how the Type is generated:

    private Type GetDynamicTypeForGroup<T>(IEnumerable<string> members)
    {
        var type = typeof(T);
        var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
            new AssemblyName(Guid.NewGuid().ToString()),
            AssemblyBuilderAccess.RunAndSave
        );
        var dynamicModule = dynamicAssembly.DefineDynamicModule(Guid.NewGuid().ToString());
        var typeBuilder = dynamicModule.DefineType(Guid.NewGuid().ToString());

        var properties = members.Select(prop => type.GetProperty(ObjectExtensions.NormilizePropertyName(prop)))
                            .Where(prop => prop != null)
                            .Cast<MemberInfo>();

        var fields = properties
            .Select(property => typeBuilder.DefineField(
                property.Name,
                ((PropertyInfo)property).PropertyType,
                FieldAttributes.Public
            )).Cast<FieldInfo>()
            .ToArray();

        GenerateEquals(typeBuilder, fields);
        GenerateGetHashCode(typeBuilder, fields);

        return typeBuilder.CreateType();
    }

SO, THE PROBLEM

If I use _repository.Collection<User>().GroupBy(u => new { u.Active }) it works, but if I add the Select part - .Select(s => s.Key, Count = s.Count()) (or any select statment) I got the following NotSupportedException: MemberInit

System.NotSupportedException: MemberInit em NHibernate.Linq.Visitors.HqlGeneratorExpressionVisitor.VisitExpression(Expression expression) (ommited)

My doubt is:

  • I know that NHibernate supports a Select statement with a group by and an anonymous type, but why it can't suport the Select if this type was created with the Expression Tree?

回答1:


Apparently NHibernate LINQ query translator does not support MemberInitExpression in GroupBy selector.

But why anonymous type works? Because although expression new { Active = u.Active } syntactically looks like MemberInitExpression (class initializer), in fact it isn't!

What C# compiler generates (and NHibernate supports) is a call to a constructor with parameters (NewExpression) mapped to class members through Members property - the third argument of the following Expression.New overload:

public static NewExpression New (
    ConstructorInfo constructor,
    IEnumerable<Expression> arguments,
    IEnumerable<MemberInfo> members
)

Which is the solution of the problem. Inside your dynamic type builder, generate a constructor with parameters matching the fields (and assign the corresponding fields inside the body):

var fields = properties
    .Select(property => typeBuilder.DefineField(
        property.Name,
        ((PropertyInfo)property).PropertyType,
        FieldAttributes.Public
    )).Cast<FieldInfo>()
    .ToArray();

GenerateConstructor(typeBuilder, fields); // <--

GenerateEquals(typeBuilder, fields);
GenerateGetHashCode(typeBuilder, fields);

return typeBuilder.CreateType();

and then use something like this:

private Expression<Func<T, object>> CreateGrouping<T>(IEnumerable<string> by)
{
    var keyType = GetDynamicTypeForGroup<T>(by);
    var sourceItem = Expression.Parameter(typeof(T));
    var members = keyType.GetFields();
    var arguments = members.Select(m => Expression.PropertyOrField(sourceItem, m.Name));
    var constructor = keyType.GetConstructor(members.Select(m => m.FieldType).ToArray());
    var newKey = Expression.New(constructor, arguments, members);        
    return Expression.Lambda<Func<T, object>>(newKey, sourceItem);
} 


来源:https://stackoverflow.com/questions/56079838/selection-in-groupby-query-with-nhibernate-with-dynamic-anonymous-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!