3

I have these two classes:

public class Parent
{
    public virtual string Name { get; set; }
    public virtual string Family_id { get; set; }
}

public class Children
{
    public virtual string Name { get; set; }
    public virtual DateTime BirthDate { get; set; }
    public virtual string Family_id { get; set; }
}

When I fetch a parent, I also want to fetch the oldest (ordered by BirthDate) children that has the same Family_id as the parent.

There is no foreign key between the parent and the children in the database.

(I do not want to use two different repositories, I want the functionality in the mappings)

Is property-ref something I can use?

Awesome
  • 325
  • 3
  • 6
  • 14

2 Answers2

2

One strategy would be to force an Eager Load on a Children collection and create another property to get the oldest child.

Property-Ref is used to join to another table using a column which is not the primary key.

public class Parent
{
    public virtual int Id {get; set;}
    public virtual string Name { get; set; }
    public virtual string Family_id { get; set; }
    public virtual Children OldestChild {
     get {
          return Children.OrderBy(x=>x.BirthDate).FirstOrDefault();
     }}
    public virtual IList<Children> Children {get; set;}
}

public class ParentMap : ClassMap<Parent>{
    public ParentMap(){
        Id(x=>x.Id);
        Map(x=>x.Name);
        HasMany(x=>x.Children).PropertyRef("Family_id").Fetch.Join();
    }
}

Another possibility would be to add a column to the Parent table (OldestChild_FK) and then join in that row from the Children table.

Mark Perry
  • 1,705
  • 10
  • 12
  • Thanks for your suggestion, Mark. Is it possible to do the OrderBy functionality in the mappings? – Awesome May 25 '11 at 07:41
  • You can use the `.AsSet` method on the mapping to give you an orderedSet opposed to an IList. So yes there are options to order your Children by BirthDate and have the appear in the `Children` in the correct order. – Mark Perry Sep 02 '11 at 11:03
1

I think what you want to do is create a property on the Parent called OldestChild or a list of Oldest Children and ignore that property and write some custom query (HQL or SQL) to return the results you want.

Here is a thread on ignoring properties in FluentNhibernate.

Community
  • 1
  • 1
Pieter Germishuys
  • 4,828
  • 1
  • 26
  • 34