0

I'm using fluent nhibernate, and I'm trying to map a property in my abstract base class, that can't exist on it's own, to a certain table that depends on what the derived class is.

public class UnmappedClass : Entity<Guid>
{
    // This class isn't mapped to a table on its own, its mapping depends on the class that uses it
}

public abstract class BaseClass : Entity<Guid>
{
    // mapping depends on derived class, not mapped to anything in base class
    protected IList<UnmappedClass> myList = new List<UnmappedClass>();

    public virtual IEnumerable<UnmappedClass> Stuff
    {
        get { return myList.ToList(); }
    }
}

public class DerivedClass : BaseClass
{
    // At this point, I need to map MyClass in member myList to a table specific to DerivedClass
}

I've tried the following in an override and get the error Invalid object name 'UnmappedClass'.

mapping.HasMany(Reveal.Member<DerivedClass, IEnumerable<UnmappedClass>>("myList"))
    .Table("TableName")
    .Access.Field()
    .Cascade.AllDeleteOrphan()
    .Inverse();
wired_in
  • 2,593
  • 3
  • 25
  • 32

1 Answers1

0

I am not completely sure, if this is what you want, but what about using Generics? Here is an example:

public abstract class BaseClass<T> : Entity<Guid>
    where T : UnmappedClass
{
    // mapping depends on derived class, not mapped to anything in base class
    protected IList<T> myList = new List<T>();

    public virtual IEnumerable<T> Stuff
    {
        get { return myList.ToList(); }
    }
}

public class DerivedClass : BaseClass<MyClass>
{
}

Your mapping class is also a generic base class:

public abstract class BaseClassMap<TEntity, TList> : ClassMap<TEntity>
    where TEntity : BaseClass
    where TList : UnmappedClass
{
    protected BaseClassMap()
    {
        HasMany(Reveal.Member<TEntity, IEnumerable<TList>>("myList"))
            .Table("TableName")
            .Access.Field()
            .Cascade.AllDeleteOrphan()
            .Inverse();
    }
}

public class DerivedClassMap : BaseClassMap<DerivedClass, MyClass>
{
}

I did not check, if the code compiles. You should get a table for DerivedClass that gets referenced by the table of MyClass (named "TableName").

rumpelstiefel
  • 466
  • 3
  • 5
  • We used to use generics for this. We are restructuring for other reasons, and really don't want to use generics for this situation. Also, it seems like nhibernate ignores .Table() when you're using a mapped class. It seems to only work for .net collections of native types like IDictionary – wired_in Jan 23 '13 at 22:56
  • Well then I think, I cannot help. You want different types for your HasMany statement, but without Generics, I think there is no way in FluentNHibernate, because it is type safe. You may stick to XML mappings instead. – rumpelstiefel Jan 24 '13 at 10:20