views:

137

answers:

2

New to FluentNHibernate =D

I have a parent/children classes as follows:

public class Parent
{
    public virtual int ID { get; private set; }
    public virtual string Name { get; set; }
    public virtual IList<Child> Children { get; set; }
}

public class Child
{
    public virtual int ID { get; private set; }
    public virtual string Name { get; set; }
    public virtual Parent ActiveParent { get; set; }
}

With mappings of:

public ParentMap()
{
    Id(x => x.ID);
    Map(x => x.Name);
    HasMany(x => x.Children)
     .Inverse();
     .Cascade.All();
}

public ChildMap()
{
    Id(x => x.ID);
    Map(x => x.Name);
    //Map(x => x.ActiveParent)
    // .Column(ParentID);
}

The commented out area of the child map is the question I'm currently having trouble with. I'd like to be able to create a child object and call its' parent(ie, someChild.ActiveParent), but am unsure on how to map this via the fluent interface.

The table structure for the child table holds a parentid, with the intent of lazy loading the parent object if called. Any help is always greatly appreciated.

+2  A: 
References(x => x.Parent);
mxmissile
Yep, definitely flew right over that one.
Alexis Abril
A: 

Adding to mxmissile's answer, you will want to add a LazyLoad() to the end of the References() call, and also you might want to do something like this in your configuration:

.Mappings(m =>
    m.FluentMappings.AddFromAssemblyOf<ParentMap>()
        .ConventionDiscovery.Add(ForeignKey.EndsWith("ID")))

The last line instructs Fluent NHibernate to expect foreign keys named like ParentID rather than the default (Parent_Id ?), so you no longer need to specify the column name explicitly in every relationship mapping.

Jørn Schou-Rode
Ah, thank you for the additional clarification on the configuration side. I was a little in the dark about the "magic" happening with column mappings.
Alexis Abril
Fluent NHibernate have several other conventions that you are able to change/tweak if needed. More details here: http://wiki.fluentnhibernate.org/Conventions
Jørn Schou-Rode