流畅的NHibernate和HasMany映射

时间:2012-10-30 08:38:09

标签: c# .net fluent-nhibernate mapping

我使用流利的nhibernate和HasMany有以下问题。我搜索谷歌和SO搜索类似的问题,但我发现的任何解决方案都无法解决我的问题。

我有以下entites映射(为清楚起见,我省略了大多数属性):

PaymentSchedule.cs

public class PaymentSchedule
{
    public virtual BinaryId Id { get; set; }

    public virtual IList<PaymentToSchedule> Payments { get; set; }
}

PaymentToSchedule.cs

  public class PaymentToSchedule
  {
    public virtual BinaryId Id { get; set; }        

    public virtual PaymentSchedule PaymentSchedule { get; set; }
}

映射文件

PaymentScheduleMap.cs

public class PaymentScheduleMap : ClassMap<PaymentSchedule>
{
    public PaymentScheduleMap()
    {
        Table("A_Payment_Schedule");
        Id(x => x.Id, "A_Payment_Schedule_Id").CrmId();
        HasMany<PaymentToSchedule>(x => x.Payments).Table("A_Payment_To_Schedule").KeyColumns.Add("A_Payment_Schedule_Id").Fetch.Select();
    }
}

PaymentToScheduleMap.cs

public class PaymentToScheduleMap : ClassMap<PaymentToSchedule>
{
    public PaymentToScheduleMap()
    {
        Table("A_Payment_To_Schedule");
        Id(x => x.Id, "A_Payment_To_Schedule_Id").CrmId();            
        References(x => x.PaymentSchedule, "A_Payment_Schedule_Id");            
    }
}

基本上我想在加载PaymentSchedule对象时获取PaymentToSchedule的列表。现在,要做到这一点,我必须使用这样的查询:

var paymentSchedules = dataAccess.Session.QueryOver<PaymentSchedule>().List(); 

以及每个付款时间表

 var paymentToSchedule = (from pts in dataAccess.Session.Query<PaymentToSchedule>()
                                                where pts.PaymentSchedule.Id == ps.Id).
                                                      ToList<PaymentToSchedule>();

这很好用,但有没有办法在查询PaymentSchedule时获取PaymentToSchedule的列表?

1 个答案:

答案 0 :(得分:0)

var paymentSchedules = dataAccess.Session.QueryOver<PaymentSchedule>()
    .Fetch(x => x.Payments).Eager;
    .List();

// payments are already initialised, you can safly do
var allPayments = paymentSchedules.SelectMany(ps => ps.Payments).ToList();