出于某种原因,我无法正确完成此查询,而且我不明白为什么...
我有一个名为“博客”的对象,它有一个 ID 和一个“标签”列表。
每个“标签”都有一个 ID 和一个“名称”属性。
由于这是多对多关系,我有另一个名为“blog_tags”的表连接它们。
映射看起来像这样:
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);
}
我想检索具有以下所有(一些列表)标签的博客列表。
我想做这样的事情:
public IList<Blog> Filter(string[] tags)
{
var blogs = _session.QueryOver<Blog>()
.Where(x => x.Tags.ContainsAll(tags));
return blogs.ToList();
}
我尝试了几种不同的方法,但总是遇到不同且奇怪的错误,所以我希望有人能为我指出正确的方向......
最佳答案
你应该能够用这样的东西来做到这一点:
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>();
}
编辑
下面是我所说的子查询。它不是真正的子查询,但您必须首先获得您不想包含在结果中的值列表(标签名称)。
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>();
关于c# - FluentNHibernate 查询多对多关系对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8864605/