许多一对多的关系对象FluentNHibernate查询 [英] FluentNHibernate query on many-to-many relationship objects

查看:157
本文介绍了许多一对多的关系对象FluentNHibernate查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我不能让这个查询的权利,我不明白为什么...

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

我有一个名为'博客',有一个对象一个标识,以及标签的。

每个'标签列表'有一个ID和一个名称属性。

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.

由于这是。一个多对多的关系,我已要求另一个表blog_tags将它们连接

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

的映射是这样的:

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.

我愿做这样的事情:

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...

推荐答案

您应该能够做到这一点像这样的东西:

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

这篇关于许多一对多的关系对象FluentNHibernate查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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