自定义 linq 提供程序以在 XML 字段中搜索具有特定值的 xml 属性

Custom linq provider to search into an XML field for an xml attribute with a certain value

我通过 NHibernate 与之交互的一些数据库 table 包含具有以下结构的 XML 字段:

<L xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <I>
     <C>
       <N>Attribute1</N>
       <V>a_value</V>
     </C>
     <C>
       <N>Attribute2</N>
       <V>123</V>
     </C>
  </I>
</L>

基本上,每个 "C" 标签都包含一个属性,其名称包含在标签 "N" 中,其值包含在标签 "V".

我想要实现的是能够在我的查询中编写这种 LINQ 语法:

..
.Where(m=>m.XMLField(attribute_name, attribute_value))
..

这样我就能够获取特定 table 的实体,其 XML 字段包含名为“attribute_name 的属性" 以及由“attribute_value”指定的字符串值。

就这么简单,XML结构总是那样,我只需要查询具有特定值的单个属性。

通过搜索,我发现有一种特定的技术可以实现自定义 LINQ 提供程序:

  1. http://www.primordialcode.com/blog/post/nhibernate-3-extending-linq-provider-fix-notsupportedexception
  2. http://fabiomaulo.blogspot.it/2010/07/nhibernate-linq-provider-extension.html
  3. How would I alter the SQL that Linq-to-Nhibernate generates for specific columns?

不幸的是,我找不到一些关于如何使用 treebuilder 的结构化文档,所以,目前我拥有的是:

我找到了执行此类任务的正确 HQL:

where [some other statements] and XML_COLUMN_NAME.exist('/L/I/C[N=\"{0}\" and V=\"{1}\"]') = 1","attribute_name", "attribute_value");

我将在 LINQ 查询中调用的方法:

public static bool AttributeExists(this string xmlColumnName, string attributeName, string attributeValue)
{
   throw new NotSupportedException();
}

与HQL的整合部分:

public class XMLAttributeGenerator : BaseHqlGeneratorForMethod
{
   public XMLAttributeGenerator()
   {
       SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition(() => TestClass.AttributeExists(null, null, null)) };
   }

    public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject,
        ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
    {
        return treeBuilder.Exists(???);
    }
}

如您所见,我仍然没有弄清楚如何正确使用带有访问者对象的树构建器来复制上面表达的 HQL 语法。有人可以帮我解决这个问题,或者至少给我一些关于 treebuilder 使用的基本文档吗?谢谢

这就是我达到预期结果的方式:

模拟方法

public static class MockLINQMethods
    {
        public static bool XMLContains(this MyCustomNHType input, string element, string value)
        {
            throw new NotImplementedException();
        }
}

自定义生成器

public class CustomLinqToHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
    {
        public CustomLinqToHqlGeneratorsRegistry()
            : base()
        {
            RegisterGenerator(ReflectionHelper.GetMethod(() => MockLINQMethods.XMLContains((MyCustomNHType) null, null, null)),
                              new LINQtoHQLGenerators.MyCustomNHTypeXMLContainsGenerator());
        }
}

public class MyCustomNHTypeXMLContainsGenerator : BaseHqlGeneratorForMethod
        {
            public MyCustomNHTypeXMLContainsGenerator()
            {
                SupportedMethods = new[] { ReflectionHelper.GetMethod(() => MockLINQMethods.XMLContains((MyCustomNHType) null, null, null)) };
            }

            public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject,
                ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
            {
                var column_name = visitor.Visit(arguments[0]).AsExpression();
                var element_name = visitor.Visit(arguments[1]).AsExpression();
                var value = visitor.Visit(arguments[2]).AsExpression();

                return treeBuilder.BooleanMethodCall("_ExistInMyCustomNHType", new [] { column_name, element_name, value});
            }
        }

自定义函数

public class CustomLinqToHqlMsSql2008Dialect : MsSql2008Dialect
    {
        public CustomLinqToHqlMsSql2008Dialect()
        {
            RegisterFunction("_ExistInMyCustomNHType", 
                new SQLFunctionTemplate(NHibernateUtil.Boolean, 
                    "?1.exist('/L/I/C[N=sql:variable(\"?2\") and V=sql:variable(\"?3\")]') = 1"));
        }
    }

最后,LINK会话助手中的自定义生成器和自定义函数

    factory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
    .ConnectionString(connectionString)
        .Dialect<CustomLinqToHqlMsSql2008Dialect>())
        ..
        .ExposeConfiguration(c =>
            {    
            ..         
            c.SetProperty("linqtohql.generatorsregistry", "APP.MyNAMESPACE.CustomLinqToHqlGeneratorsRegistry, APP.MyNAMESPACE");
            ..                        
            })                    
        .BuildSessionFactory();