查找与列表中所有列表元素匹配的实体 [英] Find entities that match all list elements in a list

查看:129
本文介绍了查找与列表中所有列表元素匹配的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(简化的)多对多关系:

I have the following (simplified) many-to-many relationship:

public class Tag
{
    public string Name { get; set; }
    public IList<Product> Products { get; set; }
}

public class Product
{
    public IList<Tag> Tags { get; set; }
}

以下代码段返回与至少一个标签匹配的所有产品:

The following snippet returns all products that match at least one tag:

var searchTags = new[] {"tag1", "tag3"};
Tag tagAlias = null;
var query = _session.QueryOver<Product>()
               .JoinAlias(p => p.Tags, () => tagAlias)
               .WhereRestrictionOn(() => tagAlias.Name).IsIn(searchTags)
               .List();

如何获取包含具有所有标签名称的产品的列表?

How can I achive to get a list that contains products which have all tag names?

推荐答案

假设您的Product类至少具有Id属性,则可以使用类似的方法. 如果有多个Id属性,则必须显式选择所有这些属性.

Assuming your Product class has at least Id property, you may go for something like this. If there is more than a Id property, you will have to explicitly select all these properties.

var searchTags = new[] { "tag1", "tag3" };
Tag tagAlias = null;

Product pr = null, resProduct = null;

var products = 
    session.QueryOver(() => pr)
        .JoinAlias(() => pr.Tags, () => tagAlias)
        .WhereRestrictionOn(() => tagAlias.Name).IsIn(searchTags)
        .SelectList(list => list
                                .SelectGroup(p => p.Id)
                                .SelectCount(p => tagAlias.Name))
        .Where(Restrictions.Eq(Projections.Count<Product>(p => tagAlias.Name),
                                searchTags.Length))
        .SelectList(list => list
                                .SelectGroup(p => p.Id).WithAlias(() => resProduct.Id))
        .TransformUsing(Transformers.AliasToBean<Product>())
        .List();

我敢打赌,答案不那么复杂,只是找不到.希望这会有所帮助.

I bet there is a less complex answer, just can't find it. Hope this will help anyway.

这篇关于查找与列表中所有列表元素匹配的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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