Convert to NHibernate Queryover
How do I convert fol开发者_如何学JAVAlowing SQL to NH Queryover,
select COUNT(*)
from
(select p.CODE,sl.BATCH from STORELOCATION sl
right join PRODUCT p on p.CODE = sl.CODE
group by p.CODE,sl.BATCHID)
as t
I've tried to solve it using QueryOver and Alias; sorry, but I can't test this code now. :(
ProductModel myProd = null;
StoreLocationModel myLocation = null;
var qOver = _HibSession.QueryOver<ProductModel>(() => myProd)
.JoinAlias(() => myProd.Locations, () => myLocation, JoinType.LeftOuterJoin)
.Select(Projections.GroupProperty(myProd.CODE), Projections.GroupProperty(myLocation.BATCHID))
.RowCount();
I hope it's helpful!
I have managed to achieve this using a custom projection, if anyone interested code is as follows,
[Serializable]
public class GroupCountProjection : SimpleProjection
{
private PropertyProjection[] _projections;
public GroupCountProjection(PropertyProjection[] projections)
{
_projections = projections;
}
public override bool IsAggregate
{
get { return true; }
}
public override IType[] GetTypes(ICriteria criteria, ICriteriaQuery criteriaQuery)
{
return new IType[] { NHibernateUtil.Int32 };
}
public override SqlString ToSqlString(ICriteria criteria, int position, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters)
{
SqlStringBuilder result = new SqlStringBuilder()
.Add(" count(*) as y")
.Add(position.ToString())
.Add("_ from ( select ");
for (int index = 0; index < _projections.Length; index++)
{
PropertyProjection projection = _projections[index];
if (index > 0)
result.Add(",");
result.Add(projection.ToSqlString(criteria, ++position, criteriaQuery, enabledFilters));
}
result.Add(" ");
return result.ToSqlString();
}
public override string ToString()
{
return "select count(*)";
}
public override bool IsGrouped
{
get { return true; }
}
public override SqlString ToGroupSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery,
IDictionary<string, IFilter> enabledFilters)
{
SqlStringBuilder result = new SqlStringBuilder();
for (int index = 0; index < _projections.Length; index++)
{
PropertyProjection projection = _projections[index];
if (index > 0)
result.Add(",");
result.Add(StringHelper.RemoveAsAliasesFromSql(projection.ToSqlString(criteria, 0, criteriaQuery,enabledFilters)));
}
result.Add(") as tbly");
return result.ToSqlString();
}
}
here, the constructor of the projection needs to be passed with all the group by projections like,
var countQuery = GetProductQuery(); // this is the queryover
countQuery
.Select(new GroupCountProjection(new[]{
Projections.Group(() => _productAlias.Code),
Projections.Group(() => _storeLocationAlias.Batch),
}));
int resultCount = (int)countQuery.List<object>().SingleOrDefault();
精彩评论