NHibernate one-to-many criteria query
Suppose I have a Post class and a Tag class. The relationship between Post and Tag is 开发者_开发问答one-to-many. How can I write a Hibernate query to retrieve a List of Post objects which have a given Tag?
public IList<Post> FindByTag(Tag tag)
{
IList<Post> posts;
using (ISession session = HibernateUtil.GetSessionFactory().OpenSession())
{
posts = session.CreateCriteria<Post>()
.Add(...) // what Criteria do I add?
.List<Post>();
}
return posts;
}
You need to add an Alias or Criteria
session.CreateCriteria<Post>()
.CreateAlias("Tags", "tag")
.Add(Restrictions.Eq("tag.Id", tag.Id))
.List<Post>();
精彩评论