2012-04-25 128 views
0

我有一個主實體Trnx這樣的:NHibernate的連接兩個實體,並返回另一個實體

public class MasterTrnx 
{ 
    private int? _AccountId; 
    private string _Place; 
    private DateTime _ProcessTime; 
    private int _TrnxId; 
    private decimal? _PaymentValue; 
    } 

和碩的子實體這樣的:

public class MasterTrnxDetail 
    { 
    private MasterTrnx _MasterTrnx; 
    private decimal _MasterPaymentValue; 
    private decimal _PaymentValue; 
    private int _Xid; 
    } 

一個MasterTrnx實體比MasterTrnxDetail一個多兒童。

using (ISession session = base.GetSession()) 
     { 
      try 
      { 
       tx = session.BeginTransaction(); 

       listOfMasterTrnxDetail = session.QueryOver<MasterTrnxDetail>() 
        .JoinQueryOver(d => (IEnumerable<MasterTrnx>)d.Trnx) 
        .List(); 

       tx.Commit(); 
      } 
      catch (Exception e) 
      { 
       if (tx != null) 
       { 
        tx.Rollback(); 
       } 
       throw e; 
      } 
      finally 
      { 
       session.Close(); 
      } 

      return listOfMasterTrnxDetail; 
     } 

此代碼塊正在工作。例如,我有一個主實體,它有三個masterdetail。這段代碼給了我3條記錄。但我想要一個主記錄和總計細節'MasterPaymentValues。我怎樣才能做到這一點?此外,我想方法返回像這樣的另一個實體:

public class Trnx 
{ 
    public decimal? PaymentValue { get; set; } 
    public DateTime ProcessTime { get; set; } 
    public string TrnxName { get; set; } 
    public decimal? TotalMasterPaymentValue { get; set; } 
} 

感謝您的幫助。

回答

0

類模型似乎有點奇怪,所以我只能猜測

MasterTrnx mastertx = null; 

var subquery = QueryOver.Of<MasterTrnxDetail>() 
    .Where(detail => detail.MasterTrnx = mastertx) 
    .Select(Projections.Sum<MasterTrnxDetail>(d => d.PaymentValue)); 


Trnx dto = null; 

transactions = session.QueryOver(() => mastertx) 
    .SelectList(list => list 
     .Select(t => t.ProcessTime).WithAlias(() => dto.ProcessTime) 
     .Select(t => t.Place).WithAlias(() => dto.TrnxName) 
     .Select(Projections.Subquery(subquery)).WithAlias(() => dto.TotalMasterPaymentValue) 
    ) 
    .TransformUsing(Transformers.AliasToBean<Trnx>()) 
    .List<Trnx>(); 
相關問題