Simple FluentNHibernate parent / child mapping

New to FluentNHibernate = D

I have parent / child classes like this:

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:

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 marked area of โ€‹โ€‹the child map is the question I'm having trouble with. I would like to be able to create a child object and call its parent (i.e. SomeChild.ActiveParent), but I'm not sure how to map this using the fluent interface.

The table structure for the child table contains the parent for the purpose of lazy loading the parent if called. Any help is always appreciated.

+2


source to share


2 answers


References(x => x.Parent);

      



+6


source


By adding mxmissile's answer you need to add LazyLoad()

to the end of the call References()

and also you can do something like this in your config:

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

      



The last line tells Fluent NHibernate to expect named foreign keys ParentID

rather than default ( Parent_Id

?), So you no longer need to explicitly specify the column name in every relationship mapping.

0


source







All Articles