QueryOver IList<string> 属性

QueryOver IList<string> property

我有一个映射 class,它有一个 ICollection 属性,它被映射为一个集合(通过代码映射使用)。请注意,该集合包含字符串而不是另一个映射实体。例如

public class Item
{
    public virtual ICollection<string> Facts { get; set; }  
}

public class ItemMapping
{
    public ItemMapping()
    {
        Set(x => x.Facts, m =>
        {
            m.Key(k => k.Column("ItemId"));
            m.Table("Facts");
        }, col => col.Element(m =>
        {
            m.Column("Description");
            m.Type(NHibernateUtil.String);
        }));
    }
}

这有效,并且对具有事实的项目的 CRUD 操作工作正常。

但是,我想 QueryOver<> 数据库中的事实(例如检索计数或前 20 个事实或检索一些随机事实)但如果没有实体,我该怎么做?我不想引入 Fact 实体,因为唯一的 属性 它会是一个字符串。

非实体必须由其实体查询然后选择。例如获取前 20 个事实:

string fact = null;
var first20facts = session.QueryOver<Item>()
    .JoinAlias(i => i.Facts, () => fact)
    .OrderBy(() => fact).Asc
    .Take(20)
    .Select(() => fact)
    .List<string>();

或者,您也可以为 Fact 映射一个只读实体以查询它。

嗯,我的建议是:

introduce entity. Even if it would have only one property. Later you can extend that (with Order, IsVisible). And if you will do that everywhere your framework will be built only from one-to-many and many-to-one relations among first citizens objects. That mean simple "framework generalization, reuse..."

但我看到你不喜欢它(请至少尝试重新考虑) - 所以有方式:

NHibernate How do I query against an IList property?

我试图证明 (基于文档) 我们可以使用魔法词 ".elements":

17.1.4.1. Alias and property references

所以查询将触及您案例中的字符串元素

Item item = null;
string fact = null;
var demos = session.QueryOver<Item>(() => item)
       .JoinAlias(i => i.Facts, () => fact)

        // instead of this
        // .Add(Restrictions.Eq("fact", "abc"))

        // we can use the .elements keyword
        .Where(Restrictions.Eq("fact.elements", "abc"))

        .List<Item>();

因此,通过这种方式,您可以获得 Items,其中确实有一些事实等于 "abc"