我正在尝试查询包含任何指定categoryID的对象。如果我只使用我的一个分离,我会得到正确的结果,但是当我合并它们时却没有。
我想要所有具有CategoryID 1 OR 2 OR 3和CategoryID 5的对象。有任何建议吗?
'测试'的映射:HasMany(x => x.Categories).KeyColumn(“PageVersion”)。ExtraLazyLoad();
public class Test
{
public virtual IList<PageCategory> Categories { get; set; }
}
public class PageCategory
{
public virtual int ID { get; set; }
public virtual int CategoryID { get; set; }
public virtual int PageVersion { get; set; }
}
public static Test Query()
{
var query = NHibernateHelper.OpenSession().CreateCriteria<Test>();
query.CreateAlias("Categories", "Categories", NHibernate.SqlCommand.JoinType.InnerJoin);
Junction disjunction = Restrictions.Disjunction();
disjunction.Add(Restrictions.In("Categories.CategoryID", new List<int> { 1, 2, 3}));
query.Add(disjunction);
Junction disjunction2 = Restrictions.Disjunction();
disjunction2.Add(Restrictions.In("Categories.CategoryID", new List<int> { 5 }));
query.Add(disjunction2);
}
答案 0 :(得分:0)
假设您的PageCategory
引用回Test
public virtual Test TestObject { get; set; }
并且您的Test
类具有ID
属性
public virtual int ID { get; set; }
你可以试试:
public DetachedCriteria GetDetachedCriteria(List<int> ids)
{
return DetachedCriteria
.For<PageCategory>()
.SetProjection(Projections.ProjectionList().Add(Projections.Property("ID")))
.Add(Restrictions.In("CategoryID", ids))
.Add(Restrictions.EqProperty("TestObject", "test.ID"));
}
然后
var pocos = session.CreateCriteria(typeof(Test),"test")
.Add(Subqueries.Exists(GetDetachedCriteria(new List<int> { 1, 2, 3 })))
.Add(Subqueries.Exists(GetDetachedCriteria(new List<int> { 5 })))
.List<Test>();
上一个回答 ------------------------------
不确定重复CreateAlias会起作用,但也许您可以尝试这样的事情:
var query = NHibernateHelper.OpenSession().CreateCriteria<Test>();
query.CreateAlias("Categories", "cat1", NHibernate.SqlCommand.JoinType.InnerJoin);
query.CreateAlias("Categories", "cat2", NHibernate.SqlCommand.JoinType.InnerJoin);
query.Add(Restrictions.In("cat1.CategoryID", new List<int> { 1, 2, 3}));
query.Add(Restrictions.In("cat2.CategoryID", new List<int> { 5 }));
希望这会有所帮助