我有客户和客户地址类。CustomerAddress 类具有国家/地区 n 状态对象。当我加载客户时,我也想要 CustomerAddress 并且在 customerAddress 中我只想加载 contryName 和 countryID 其他详细信息必须为空。
简而言之,我想通过 Criteria APT 生成的 SQL 查询是
SELECT Customer.Name, Country.CountryName,
Country.CountryID AS CountryID,
CustomerAddress.LocalAddressLine1
FROM Customer INNER JOIN CustomerAddress
ON Customer.CustomerID = CustomerAddress.CustomerID
INNER JOIN Country
ON CustomerAddress.CountryID = Country.CountryID
为了实现这一点,我做到了
ICriteria criteria = session.CreateCriteria(typeof(Customer), "Customer")
.CreateAlias("Customer.CustomerAddressList", "CustomerAddressList", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.CreateCriteria("CustomerAddressList.Country", "Country", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.SetProjection(Projections.ProjectionList().Add(Projections.Property("Country.CountryID"))
.Add(Projections.Property("Country.CountryName")))
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(Customer)))
.Add(Restrictions.Eq("Customer.EstablishmentId", CustomerId));
但这给了我错误。怎么能这样。
如何使用 Criteria API 获取指定的列。?
根据@Firo 的指导编辑
我.Add(Restrictions.Eq("Customer.EstablishmentId", CustomerId))
以前搬过SetProjection
所以我的代码现在是
ICriteria criteria = session.CreateCriteria(typeof(Customer), "Customer")
.CreateAlias("Customer.CustomerAddressList", "CustomerAddressList", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.CreateCriteria("CustomerAddressList.Country", "Country", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.Add(Restrictions.Eq("Customer.EstablishmentId", CustomerId))
.SetProjection(Projections.ProjectionList().Add(Projections.Property("Country.CountryID"))
.Add(Projections.Property("Country.CountryName")))
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(Customer)));
customer = criteria.UniqueResult<Customer>();
这将成功执行,不会发生错误,但是当我查找customer
对象时,它的所有属性都是null
.