FluentNHibernate query on many-to-many relationshi

2020-04-11 11:02发布

For some reason i can't get this query right, and i can't understand why...

I have an object called 'Blog' that has an Id, and a list of 'Tag's.
Each 'Tag' has an id and a 'Name' property.

Since this is a many to many relationship, I have another table called 'blog_tags' connecting them.

The mappings look like this :

public class BlogsMapping : ClassMap<Blog>
{
    Table("blogs");
    Id(x => x.Id).GeneratedBy.Identity();
    Map(x => x.Content);
    HasManyToMany(x => x.Tags)
        .Table("Blog_Tags")
        .ParentKeyColumn("BlogId")
        .ChildKeyColumn("TagId")
        .Not.LazyLoad()
        .Cascade.All();
}

public class TagsMapping : ClassMap<Tag>
{
    Table("tags");
    Id(x => x.Id).GeneratedBy.Identity();
    Map(x => x.Name);
}

I would like to retrieve a list of blogs that have all of the following (some list) of tags.

I would like to do something like this :

public IList<Blog> Filter(string[] tags)
{
    var blogs = _session.QueryOver<Blog>()
        .Where(x => x.Tags.ContainsAll(tags));
    return blogs.ToList();
}

I tried a couple of different ways, but always run into different and weird errors, so i was hoping that someone could just point me in the right direction...

1条回答
可以哭但决不认输i
2楼-- · 2020-04-11 12:07

You should be able to do it with something like this:

string[] tagNames = new string[2]{ "Admins", "Users" };

using (NHibernate.ISession session = SessionFactory.GetCurrentSession())
{
    IList<Blog> blogsFound = session.QueryOver<Blog>()
                                    .Right.JoinQueryOver<Tags>(x => x.Tags)
                                    .WhereRestrictionOn(x => x.Name).IsIn(tagNames)
                                    .List<Blog>();

}

Edit

The below is what I was talking about with the subquery. It's not really a subquery but you have to 1st get a list of values (tag names) that you don't want to include in your results.

string[] tagNames = new string[2]{ "Admins", "Users" };
IList<string> otherTags = 
    session.QueryOver<Tag>()
           .WhereRestrictionOn(x => x.Name).Not.IsIn(tagNames)
           .Select(x => x.Name)
           .List<string>();

string[] otherTagNames = new string[otherTags.Count];
otherGroups.CopyTo(otherTagNames, 0);

IList<Blog> blogsFound = 
    session.QueryOver<Blog>()
           .Right.JoinQueryOver<Tag>(x => x.Tags)
           .WhereRestrictionOn(x => x.Name).IsIn(tagNames)
           .WhereRestrictionOn(x => x.Name).Not.IsIn(otherTagNames)
           .List<Blog>();
查看更多
登录 后发表回答