我有一个带有集合(InvoiceRows)的类(Invoice)。
课程 -
public class Invoice
{
public string ID {get; set;}
public List<InvoiceRow> InvoiceRows {get; set;}
}
public class InvoiceRow
{
public string ID { get; set;}
public string InvoiceID { get; set;}
public int RowNumber { get; set;}
}
映射 -
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Domain.BusinessClasses.Invoice" table="Invoices" lazy="false">
<id name="ID">
<column name="ID"/>
<generator class="assigned"/>
</id>
<bag name="InvoiceRows" lazy="false" cascade="save-update" inverse="true" order-by="InvoiceRowNumber">
<key column="InvoiceID"/>
<one-to-many class="Domain.BusinessClasses.InvoiceRow" />
</bag>
</class>
<class name="Domain.BusinessClasses.InvoiceRow" table="InvoiceRows" lazy="false">
<id name="ID">
<column name="ID"/>
<generator class="assigned"/>
</id>
<property name="InvoiceID">
<column name="InvoiceID"/>
</property>
<property name="RowNumber">
<column name="RowNumber"/>
</property>
</class>
我希望获得所有InvoiceRow的InvoiceRow,其中RowNumber = 1 和 RowNumber = 2.最好使用ICriterion API。
答案 0 :(得分:3)
我设法根据Genius回答找到答案。
var dCriteria1 = DetachedCriteria.For<InvoiceRow>("r")
.SetProjection(Projections.Property("r.RowNumber"))
.SetProjection(Projections.Property("r.InvoiceID")) // Must be last!!!!
.Add(Restrictions.Eq("r.RowNumber", 1));
var dCriteria2 = DetachedCriteria.For<InvoiceRow>("r")
.SetProjection(Projections.Property("r.RowNumber"))
.SetProjection(Projections.Property("r.InvoiceID")) // Must be last!!!!
.Add(Restrictions.Eq("r.RowNumber", 2));
var invoices = Session.CreateCriteria<Invoice>()
.Add(Subqueries.PropertyIn("ID", dCriteria1))
.Add(Subqueries.PropertyIn("ID", dCriteria2))
.List<Invoice>();
答案 1 :(得分:2)
应该看起来像这样(未选中!):
var dCriteria1 = DetachedCriteria.For<InvoiceRow>("r")
.Add(Restrictions.EqProperty("r.InvoiceID", "i.ID"))
.Add(Restrictions.Eq("r.RowNumber", 1));
var dCriteria2 = DetachedCriteria.For<InvoiceRow>("r")
.Add(Restrictions.EqProperty("r.InvoiceID", "i.ID"))
.Add(Restrictions.Eq("r.RowNumber", 2));
var invoices = Session.CreateCriteria<Invoice>("i")
.Add(Subqueries.Exists(dCriteria1))
.Add(Subqueries.Exists(dCriteria2))
.List<Invoice>();
可能是这个代码可以优化,但想法就是这样。
答案 2 :(得分:0)
List<int> list=new List<int>();
list.Add(1);
list.Add(2);
DetachedCriteria forInvoice=DetachedCriteria.For<Invoice>();
DetachedCriteria forInvoiceRow=forInvoice.CreateCriteria("InvoiceRows");
forInvoiceRow.Add(Expression.In("RowNumber",list));
ICriteria executableCriteria = forInvoice.GetExecutableCriteria(Session);
executableCriteria.List<Invoice>();