NHibernate的我如何查询针对一个IList<串GT;属性? [英] NHibernate How do I query against an IList<string> property?

查看:97
本文介绍了NHibernate的我如何查询针对一个IList<串GT;属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查询使用的一个IList<串GT;财产上使用NHibernate我的领域类之一。下面是一个简单的例子来说明:

I am trying to query against an IList<string> property on one of my domain classes using NHibernate. Here is a simple example to demonstrate:

public class Demo
{
    public Demo()
    {
        this.Tags = new List<string>();
    }
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<string> Tags { get; set; }
}

这样映射:

<class name="Demo">
<id name="Id" />
<property name="Name" />
<bag name="Tags">
  <key column="DemoId"/>
  <element column="Tag" type="String" />
</bag>

和我能够保存和检索就好了。我们查询所在的标签属性包含一个指定的值我的域名类的实例:

And I am able to save and retrieve just fine. Now to query for instances of my domain class where the Tags property contains a specified value:

var demos = this.session.CreateCriteria<Demo>()
            .CreateAlias("Tags", "t")
            .Add(Restrictions.Eq("t", "a"))
            .List<Demo>();

错误结果:收集是不是关联:Demo.Tags

Results in the error: collection was not an association: Demo.Tags

var demos = (from d in this.session.Linq<Demo>()
                     where d.Tags.Contains("a")
                     select d).ToList();

在错误结果:Objct引用不设置为一个对象的一个​​实例

Results in the error: Objct reference not set to an instance of an object.

var demos = this.session.CreateQuery("from Demo d where :t in elements(d.Tags)")
            .SetParameter("t", "a")
            .List<Demo>();

工作正常,但我的真实域名类有很多很多的属性,我建立一个复杂的动态查询,做丑陋的字符串操作是不是我的第一选择。我宁愿使用的ICriteria或LINQ。我有一个可以输入多个不同的可能的搜索条件的用户界面。在code现在这种权利建立起来的ICriteria是几十排长队。我真的不想将其转换成HQL字符串操作。

Works fine, but as my real domain class has many many properties, and I am building a complicated dynamic query, doing ugly string manipulation is not my first choice. I'd much rather use ICriteria or Linq. I have a user interface where many different possible search criteria can be entered. The code that builds up the ICriteria right now is dozens of lines long. I'd really hate to turn that into HQL string manipulation.

推荐答案

所以因为标准API的限制,我决定让我的领域类,以适应。

So because of limitations of the Criteria API, I decided to bend my domain classes to fit.

我创建了一个实体类的标签。我甚至不能将其创建为一个值对象。它必须有其自己的ID。

I created an entity class for the Tag. I couldn't even create it as a value object. It had to have its own id.

我现在觉得脏。但是,除了坚守域能够构建一个动态查询,而不诉诸字符串操作对我来说更重要。

I feel dirty now. But being able to construct a dynamic query without resorting to string manipulation was more important to me than staying true to the domain.

这篇关于NHibernate的我如何查询针对一个IList&LT;串GT;属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆