简体   繁体   English

NHibernate搜索条件

[英]NHibernate search criteria

I have class Definition with property string Data 我有带有属性字符串Data的类Definition

public class Definition
{
  string Type  {get; set; }
  string Data  { get; set; }
}

Then Data contains some XML that saved as string 然后数据包含一些另存为字符串的XML

<Definition>
    <Property>
     <Key>DefinitionId</Key>
     <Value>5</Value>
    </Property>   
</Definition>

I need to get all Definitons where DefinitionId is 5. 我需要获取DefinitionId为5的所有Definitons。

What the best way to do it? 最好的方法是什么? To get all definitions and parsed them or i can do something with NHibernate? 要获取所有定义并进行解析,或者我可以使用NHibernate做一些事情?

You can query Xml types with NHibernate if your DB supports Xml querying. 如果您的数据库支持Xml查询,则可以使用NHibernate查询Xml类型。 Assuming you're working with Sql Server 2005+ ... 假设您正在使用Sql Server 2005+ ...

Step 1 - Class Definition 步骤1- 类别定义

Change your class Definition to: 将您的班级定义更改为:

public class Definition
{
  string Type  {get; set; }
  XDocument Data  { get; set; }
}

Your mapping should pick the XDocument type and create a the appropriate Xml column type for the Data column in the database. 您的映射应选择XDocument类型,并为数据库中的Data列创建适当的Xml列类型。

Step 2 - Querying 第2步- 查询

A couple of different ways to query, but they boil down to the same thing. 几种不同的查询方式,但是归结为同一件事。 The code below shows the querying via the QueryOver api: 下面的代码显示了通过QueryOver api进行的查询:

session.QueryOver<Definition>()
       .Where
        (
            Restrictions.Eq
            (
                Projections.SqlProjection
                (
                   "Data.value('(/Definition/Property/Value)[1]', 'int') as DefinitionId",
                   new string[] { "DefinitionId" },
                   new IType[] { NHibernateUtil.Int32 }
                ),
                5
            )
        )
       .List();

The above query uses standard Sql Server XQuery to query the Xml field. 上面的查询使用标准的Sql Server XQuery查询Xml字段。 A little introduction on XQuery language: http://blog.sqlauthority.com/2012/04/27/sql-server-introduction-to-discovering-xml-data-type-methods-a-primer/ 关于XQuery语言的一些简介: http : //blog.sqlauthority.com/2012/04/27/sql-server-introduction-to-discovering-xml-data-type-methods-a-primer/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM