FluentNHibernate query on many-to-many relationship objects

妖精的绣舞 提交于 2019-12-31 02:20:09

问题


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:


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>();


来源:https://stackoverflow.com/questions/8864605/fluentnhibernate-query-on-many-to-many-relationship-objects

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