Lambda string as VARCHAR

橙三吉。 提交于 2019-12-12 01:34:53

问题


One of my Join key-selectors looks like this:

x => x.A + "-" + x.B

NHibernate makes "-" an extra parameter. This parameter gets the SQL type nvarchar and so the whole statement gets converted on the SQL Server from varchar to nvarchar.

The problem with this is, that SQL Server has a huge problem if the queried column is of type varchar instead of nvarchar. This is because the column is of another type than the parameter and so the index can't be used.

I cannot change the type of the column so I need to define somehow that NHibernate should use varchar for string literals when converting lambdas.

Any way to do this?

UPDATE

With help from Oskar Berggren I setup this classes:

public static class VarcharFix
    {
        /// This method returns its argument and is a no-op in C#.
        /// It's presence in a Linq expression sends a message to the NHibernate Linq Provider.
        public static string AsVarchar(string s)
        {
            return s;
        }
    }

public class MyHqlIdent : HqlExpression
    {
        internal MyHqlIdent(IASTFactory factory, string ident)
            : base(HqlSqlWalker.IDENT, ident, factory)
        {
        }

        internal MyHqlIdent(IASTFactory factory, System.Type type)
            : base(HqlSqlWalker.IDENT, "", factory)
        {
            if (IsNullableType(type))
            {
                type = ExtractUnderlyingTypeFromNullable(type);
            }

            switch (System.Type.GetTypeCode(type))
            {
                case TypeCode.Boolean:
                    SetText("bool");
                    break;
                case TypeCode.Int16:
                    SetText("short");
                    break;
                case TypeCode.Int32:
                    SetText("integer");
                    break;
                case TypeCode.Int64:
                    SetText("long");
                    break;
                case TypeCode.Decimal:
                    SetText("decimal");
                    break;
                case TypeCode.Single:
                    SetText("single");
                    break;
                case TypeCode.DateTime:
                    SetText("datetime");
                    break;
                case TypeCode.String:
                    SetText("string");
                    break;
                case TypeCode.Double:
                    SetText("double");
                    break;
                default:
                    if (type == typeof(Guid))
                    {
                        SetText("guid");
                        break;
                    }
                    if (type == typeof(DateTimeOffset))
                    {
                        SetText("datetimeoffset");
                        break;
                    }
                    throw new NotSupportedException(string.Format("Don't currently support idents of type {0}", type.Name));
            }
        }

        private static System.Type ExtractUnderlyingTypeFromNullable(System.Type type)
        {
            return type.GetGenericArguments()[0];
        }

        // TODO - code duplicated in LinqExtensionMethods
        private static bool IsNullableType(System.Type type)
        {
            return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
    }

    public class MyHqlCast : HqlExpression
    {
        public MyHqlCast(IASTFactory factory, IEnumerable<HqlTreeNode> children)
            : base(HqlSqlWalker.METHOD_CALL, "method", factory, children)
        {

        }

        public static MyHqlCast Create(IASTFactory factory, HqlExpression expression, string targetType)
        {
            return new MyHqlCast(factory,
                                new HqlTreeNode[]
                                {
                                    new MyHqlIdent(factory, "cast"),
                                    new HqlExpressionList(factory, expression,
                                    new MyHqlIdent(factory, targetType))
                                });
        }
    }

    public class MyBaseHqlGeneratorForMethod : BaseHqlGeneratorForMethod
    {
        public MyBaseHqlGeneratorForMethod()
            : base()
        {
            SupportedMethods = new MethodInfo[] { typeof(VarcharFix).GetMethod("AsVarchar") };
        }

        public override HqlTreeNode BuildHql(MethodInfo method, System.Linq.Expressions.Expression targetObject, System.Collections.ObjectModel.ReadOnlyCollection<System.Linq.Expressions.Expression> arguments, HqlTreeBuilder treeBuilder, global::NHibernate.Linq.Visitors.IHqlExpressionVisitor visitor)
        {
            return MyHqlCast.Create(new ASTFactory(new ASTTreeAdaptor()),
                        visitor.Visit(targetObject).AsExpression(),
                        "varchar");
        }
    }

public class ExtendedLinqtoHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
    {
        public ExtendedLinqtoHqlGeneratorsRegistry()
        {
            this.Merge(new MyBaseHqlGeneratorForMethod());
        }
    }

For now it's still not working but I see light ;)

UPDATE 2: The Query

var query = aQueryable
            .Join(bQueryable,
        x => x.AB, x => x.A + VarcharFix.AsVarchar("-") + x.B,
                                (head, middle) => new ...)

UPDATE 3:

As "-".AsVarchar() gets optimized to "-" we need a dummy parameter, which cannot be optimized like "-".AsVarchar(x.A) - that way the Linq-extension kicks in!

var query = aQueryable
            .Join(bQueryable,
        x => x.AB, x => x.A + "-".AsVarchar(x.A) + x.B,
                                (head, middle) => new ...)

回答1:


There may be multiple ways to do this but here is one:

Invent your own method such as:

/// This method returns its argument and is a no-op in C#.
/// It's presence in a Linq expression sends a message to the NHibernate Linq Provider.
public static string AsVarchar(string s)
{
    return s;
}

Also create a class to represent the HQL expression fragment:

public class MyHqlCast : HqlExpression
{
    private MyHqlCast(IASTFactory factory, IEnumerable<HqlTreeNode> children)
        : base(HqlSqlWalker.METHOD_CALL, "method", factory, children)
    {
    }

    public static MyHqlCast Create(IASTFactory factory, HqlExpression expression,
                                   string targetType)
    {
        return new MyHqlCast(factory,
                             new [] {
                                 new HqlIdent(factory, "cast")),
                                 new HqlExpressionList(factory, expression,
                                         new HqlIdent(factory, targetType)),
                             });
    }
}

Then derive a class from BaseHqlGeneratorForMethod. In its constructor, set the SupportedMethods property to the AsVarchar() method. Override the BuildHql() method. It should output the HQL cast constructs equivalent to cast(@param as varchar). Normally you would use the Cast() method on the treeBuilder parameter, but unfortunately this accepts just a System.Type, which isn't good enough for this case. Instead create and return an instance of your MyHqlCast:

return MyHqlCast.Create(new ASTFactory(new ASTTreeAdaptor()),
                        visitor.Visit(arguments[0]).AsExpression(),
                        "varchar");

Your implementation of BaseHqlGeneratorForMethod then needs to be registered by deriving from DefaultLinqToHqlGeneratorsRegistry. Call this.Merge(new MyGenerator()); in the constructor. Then register your registry type by

nhibernateConfiguration.LinqToHqlGeneratorsRegistry<MyRegistry>();


来源:https://stackoverflow.com/questions/14396166/lambda-string-as-varchar

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