问题
I have a base class for all my entity types which is like
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 table-per-class strategy but how to map this EntityBase class? I tryed public class EntityBaseMap:ClassMap but it doesnt work.
So how could i map this class? The reason why I want that is I dont want to write the repetetive stuff with Id(c=c.ID).Not.Null .... etc but have it in one mapping class.
my mapping class look like this
public class EntityBaseMap : ClassMap<EntityBase<???>>
what should i insert instead of ???
Thanks
回答1:
In NHibernate you can't map a class with an open generic, such as EntityBase<TEntityType>. Unfortunately you'll have to define a mapping class for each of the entities:
public class MyEntityMap : ClassMap<EntityBase<MyEntity>>
{
...
}
回答2:
Still you can simplify the process via 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);
}
}
回答3:
As a workaround you could define a non-generic "Proxy" class that will be implemented by EntityBaseMap:
public abstract class EntityProxy:IEntityBase
{
public virtual Int Id {get; set;}
/* Shared properties/ repetitive mappings */
}
And mapping with
public class EntityProxyMap : ClassMap<EntityProxy>
{
/* Mapping*/
}
So you will then be able to create the EntityBase by
public abstract class EntityBase<TEntityType> : EntityProxy where TEntityType : EntityBase<TEntityType>
{
/* Your implementation */
}
And finally use a
public class YourSubclassMap : SubclassMap<EntityBase<YourSubclass>>
{
/* Do any necessary sub-class mapping */
}
来源:https://stackoverflow.com/questions/9631384/map-generic-entitybasetentity-class-with-fluentnhibernate