LAMBDA字符串VARCHAR(Lambda string as VARCHAR)

2019-11-01 10:40发布

我的一个连接键,选择的是这样的:

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

NHibernate的做"-"一个额外的参数。 此参数获取SQL类型nvarchar等整个语句被转换在SQL Server上从varcharnvarchar

这里的问题是,SQL Server有一个巨大的问题 ,如果所查询的列类型varchar ,而不是nvarchar 。 这是因为该列是另一种类型的大于该参数的,因此不能被使用索引

所以我需要以某种方式定义NHibernate的lambda表达式转换时, 应使用VARCHAR的字符串字面我不能改变列的类型。

没有办法做到这一点?

UPDATE

从奥斯卡·伯格伦我设置这个类的帮助:

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());
        }
    }

现在它仍然没有工作,但我看光;)

更新2:查询

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

更新3:

作为"-".AsVarchar()得到优化,以 "-"我们需要一个虚拟的参数 ,它不能像优化"-".AsVarchar(xA) -这样的LINQ的扩展踢!

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

Answer 1:

可以有多种方式来做到这一点,但这里是一个:

创造你自己的方法,如:

/// 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;
}

也创建一个类来表示HQL表达片段:

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)),
                             });
    }
}

然后从获得一个BaseHqlGeneratorForMethod类。 在其构造中,设置SupportedMethods属性到AsVarchar()方法。 覆盖BuildHql()方法。 它应该输出的HQL投构造相当于投(@参数为varchar)。 通常你会使用在TreeBuilder作为参数的演员()方法,但不幸的是这只是接受一个System.Type的,这是不够好这种情况。 相反创建并返回您MyHqlCast的实例:

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

你的实现BaseHqlGeneratorForMethod的则需要由DefaultLinqToHqlGeneratorsRegistry获得注册。 呼叫this.Merge(新MyGenerator()); 在构造函数中。 然后,通过注册登记类型

nhibernateConfiguration.LinqToHqlGeneratorsRegistry<MyRegistry>();


文章来源: Lambda string as VARCHAR