使用SQL查询时的ServiceStack LoadReferences

时间:2015-05-12 00:55:03

标签: c# sql-server servicestack ormlite-servicestack

是否可以在不使用以下代码的情况下加载引用:

SqlExpression<Customer> q = db.From<Customer>();
q.Join<Customer,CustomerAddress>((cust,address) => cust.Id == address.CustomerId);

List<Customer> dbCustomers = db.LoadSelect(q);

使用此:

public class KpiTotal : IKpiTotal
{
    public DateTime Date { get; set; }

    public int TeamId { get; set; }
    public Team Team { get; set; }

    public int AccountId { get; set; }
    public Account Account { get; set; }

    public double Total { get; set; }
}

var result = dbCon.SelectFmt<KpiTotal>(@"select convert(date, t.TransactionDate) [Date], tm.TeamId,a.AccountNumber, count(distinct(t.RequisitionNumber)) Total
                                    from task.tblTransactions t
                                    inner join task.tblRequisitions r on r.RequisitionNumber = t.RequisitionNumber
                                    inner join task.tblAccounts a on a.AccountNumber = r.AccountNumber
                                    inner join Team tm on tm.DivisionId = a.DivisionId
                                    where t.TransactionTypeNumber = 201 and a.IsActive = 1 
                                    and t.TransactionDate between {0} and {1}
                                    group by convert(date, t.TransactionDate), tm.TeamName, a.AccountName
                                    order by 1,2 desc", dateRange.Start, dateRange.End);

因为我的结果对象(KpiTotal)引用了两个子表,并且我想自动加载引用,而不是使用foreach块获取它。

1 个答案:

答案 0 :(得分:1)

我假设您要加载上述查询中的TeamAccountLoadSelect方法嗅探POCO模型并生成一个查询,该查询根据与您查询的核心对象的外键关系拉回所有相关的DB记录。它为每个引用/加入的POCO(非常伪编码)生成类似于此的查询:

SELECT * FROM Team /* Related POCO */
WHERE Team.Id IN (SELECT TeamId FROM [original query with WHERE clase])

基本上,只需一次查询即可恢复所有TeamsAccounts

使用ServiceStack.OrmLite v4.0.40,现在有一个新的Merge extension method,它将基于更加手动的过程将对象引用拼接在一起。

在您的情况下,您可以查询KpiTotal结果,然后只运行两个单独的查询来获取TeamAccount列表,然后合并它们。基本上:

var result = dbCon.SelectFmt<KpiTotal>(/* gnarly SQL */);
var teams = dbCon.Select(/* get all relevant teams */);
var accounts = dbCon.Select(/* get all relevant accounts */);

result.Merge(teams);
result.Merge(accounts);

Debug.WriteLine(result.Dump());    // Output to console / debug window, whatever