Find entities that match all list elements in a list

…衆ロ難τιáo~ 提交于 2019-12-11 07:45:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18871722/find-entities-that-match-all-list-elements-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!