NHibernate 如何查询 IList<string>财产? [英] NHibernate How do I query against an IList&lt;string&gt; property?

查看:23
本文介绍了NHibernate 如何查询 IList<string>财产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查询 IList;我使用 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>

而且我能够很好地保存和检索.现在查询我的域类的实例,其中 Tags 属性包含指定值:

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

导致错误:未将对象引用设置为对象的实例.

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.我有一个用户界面,可以在其中输入许多不同的可能搜索条件.现在构建 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.

推荐答案

因此,由于 Criteria 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<string>财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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