开发者

Fluent NHibernate: Map property without foreign key?

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 diffe开发者_如何学Crent repositories, I want the functionality in the mappings)

Is property-ref something I can use?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜