2015-05-12 63 views
0

是否有可能加載引用時,而不是使用下面的代碼:ServiceStack LoadReferences使用SQL查詢

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

我假設你想從上面的查詢中加載TeamAccountLoadSelect方法嗅探POCO模型並生成一個查詢,該查詢根據您正在查詢的核心對象的外鍵關係拉回所有相關的數據庫記錄。它產生類似於此對於每個被引用的一個查詢/接合POCO(非常僞編碼):

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

基本上,它在單個查詢帶回所有Teams S或Accounts

隨着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