Generic class map EntityBase <TEntity> with FluentNHibernate
I have a base class for all my entity types that is similar to
public abstract class EntityBase<TEntityType> : IEntityBase where TEntityType : EntityBase<TEntityType>
{
private List<IBusinessRule> _brokenRules = new List<IBusinessRule>();
private int? _hashCode;
public int ID { private set; get; }
and in my mappings I would like to use the table per class strategy, but how do I map this class to EntityBase? I tried public class EntityBaseMap: ClassMap but it doesn't work. So how can I map this class? The reason I want this is, I don't want to write repeating things with Id(c=c.ID).Not.Null ....
, etc., but have it in the same mapping class.
my display class looks like this
public class EntityBaseMap : ClassMap<EntityBase<???>>
what should i insert instead of <
thank
source to share
In NHibernate, you cannot map a class to a public generic , eg EntityBase<TEntityType>
. Unfortunately, you will need to define a display class for each of the objects:
public class MyEntityMap : ClassMap<EntityBase<MyEntity>>
{
...
}
source to share
However, you can simplify the process through reflection by creating a generic mapping and then using runtime typing instead of creating static types:
private static void AddWeakReferenceMappings(FluentMappingsContainer container, Assembly assembly)
{
var genericMappingType = typeof (WeakReferenceMap<>);
var entityTypes = assembly.GetTypes().Where(type => type.IsSubclassOf(typeof (Entity)));
foreach (var enitityType in entityTypes)
{
var newType = genericMappingType.MakeGenericType(enitityType);
container.Add(newType);
}
}
source to share
As a workaround, you can define a non-generic Proxy class to be implemented EntityBaseMap
:
public abstract class EntityProxy:IEntityBase
{
public virtual Int Id {get; set;}
/* Shared properties/ repetitive mappings */
}
And display with
public class EntityProxyMap : ClassMap<EntityProxy>
{
/* Mapping*/
}
So, you can create EntityBase
on
public abstract class EntityBase<TEntityType> : EntityProxy where TEntityType : EntityBase<TEntityType>
{
/* Your implementation */
}
And finally use
public class YourSubclassMap : SubclassMap<EntityBase<YourSubclass>>
{
/* Do any necessary sub-class mapping */
}
source to share