简体   繁体   中英

Fluent NHibernate and HasMany mapping

I have following problem using fluent nhibernate and HasMany. I've search through google and SO for similar problem but any of solutions I've found does not solve my problem.

I have following entites mapped (I omitted most properties for clarity):

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

Mapping files

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

Basically I want to fetch list of PaymentToSchedule entites when loading PaymentSchedule object. Now, to do this, I must use such queries:

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

and for each of the payment schedule

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

This works fine, but is there a way to fetch list of PaymentToSchedule entites while querying PaymentSchedule?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM