[英]FluentNHibernate query on many-to-many relationship objects
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. 我有一个名为'Blog'的对象,它有一个Id和一个'Tag'列表。
Each 'Tag' has an id and a 'Name' property. 每个'标签'都有一个id和一个'Name'属性。
Since this is a many to many relationship, I have another table called 'blog_tags' connecting them. 由于这是一个多对多关系,我有另一个名为'blog_tags'的表连接它们。
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... 我尝试了几种不同的方法,但总是遇到不同的奇怪错误,所以我希望有人可以指出我正确的方向......
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>();
}
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>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.