8

Say we have two classes that each implement an interface, IParent, as follows:

public class Foo : IParent
{
    public long Id { get; set; }
    ...
    public IList<Child> Children { get; set; }
    ...
}
public class Bar : IParent
{
    public long Id { get; set; }
    ...
    public IList<Child> Children { get; set; }
    ...
}

And a child class that has a parent property of the type IParent, i.e. the parent could be either a Foo or a Bar:

public class Child
{
    public long Id { get; set; }
    ...
    public IParent Parent { get; set; }
    ...
}

How can this Parent property be mapped with FluentNHibernate?

I found this question which seemed to have similar requirements, but did not involve interfaces. The answer does not really make sense to me, or seem applicable in this case.

I have tried implementing the mapping using ReferencesAny, as follows:

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Table("children");
        Id(x => x.Id).GeneratedBy.Assigned();
        ...
        ReferencesAny(x => x.Parent)
            .AddMetaValue<Foo>(typeof(Foo).Name)
            .AddMetaValue<Bar>(typeof(Bar).Name)
            .EntityTypeColumn("parent_name")
            .EntityIdentifierColumn("parent_id")
            .IdentityType<long>()
            .LazyLoad();
    }
}

This does not cause any error when saving, but no data is written to the child table in the database, leading me to believe I have implemented the mapping incorrectly.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64

0 Answers0