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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top