nhibernate加入两个实体并返回另一个实体

时间:2012-04-25 08:02:28

标签: nhibernate queryover

我有一个像这样的主要实体Trnx:

 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;
        }

此代码块正常运行。例如,我有一个主实体,它有3个三个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; }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分: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>();
相关问题