如何使用Castle ActiveRecords和LINQ或HQL执行以下查询?
选择a.id,s.classes,COUNT(p.id),MAX(p.date)AS last,MIN(p.date)AS first
来自帐户a LEFT JOIN school s ON s.account_id = a.id
LEFT JOIN用户u ON u.account_id = a.id
LEFT JOIN点p ON p.user_id = u.id
付款=" S"
GROUP BY a.id
表格按以下方式相关:
我也为所有表定义正确关系的表都有ActiveRecord类(如果我按步骤进行查询,但是因为有很多行,所以它很慢)我试过以下没有做过的事情。工作:
var result = from account in AccountRecord.Queryable
join s in SchoolRecord.Queryable on account equals s.Account into schools
from school in schools.DefaultIfEmpty(null)
join user in UserRecord.Queryable on account equals user.Account
join p in PointsRecord.Queryable on user equals p.User into points
where account.PaymentType == "S"
select new { Account = account, School = school, Count = points.Count() };
引发了以下The method or operation is not implemented
- 例外情况:
NHibernate.Linq.Visitors.QueryModelVisitor.VisitGroupJoinClause(GroupJoinClause groupJoinClause,QueryModel queryModel,Int32 index)
答案 0 :(得分:1)
使用HQL找到解决方案 - 我仍然可以使用LINQ解决方案:
HqlBasedQuery query = new HqlBasedQuery(typeof(AccountRecord),
"SELECT a, s, COUNT(p), MIN(p.DateUTC), MAX(p.DateUTC) " +
"FROM AccountRecord a " +
"LEFT JOIN a.Schools s " +
"LEFT JOIN a.Users u " +
"LEFT JOIN u.Points p " +
"WHERE a.PaymentType=:payment GROUP BY a.Id");
query.SetParameter("payment", "S");
var result = from object[] row in (ArrayList)ActiveRecordMediator.ExecuteQuery(query)
select new
{
Account = row[0] as AccountRecord,
School = row[1] as SchoolRecord,
Count = row[2],
First = (new DateTime(1970, 1, 1, 0, 0, 0, 0)).AddSeconds(Convert.ToDouble(row[3])),
Last = (new DateTime(1970, 1, 1, 0, 0, 0, 0)).AddSeconds(Convert.ToDouble(row[4]))
};
答案 1 :(得分:0)
我认为您的Linq查询类似于:
var result = from a in AccountRecord.Queryable
join s in SchoolRecord.Queryable on a.id equals s.account_id
join u in UserRecord.Queryable on a.id equals u.account_id
join p in PointsRecord.Queryable on u.id equals p.user_id
where a.payment == "S"
group by a.id
select new
{
Account = a,
School = s,
Count = p.Count()
};
虽然我不确定NHibernate将如何处理group by
和Count()
组合。您可能希望查看生成的SQL最终是什么,如果它没有引发错误。
如果这不起作用,您可能希望重新选择记录,并在应用程序中对它们进行分组/计数,更像是:
var data = from a in AccountRecord.Queryable
join s in SchoolRecord.Queryable on a.id equals s.account_id
join u in UserRecord.Queryable on a.id equals u.account_id
join p in PointsRecord.Queryable on u.id equals p.user_id
where a.payment == "S"
select new
{
Account = a,
School = s,
Count = c
};
var grouped = data.ToList.GroupBy(x => x.Account.Id);