To centralize some of my logic for each FluentNHibernate class mapping (specifically for mapping auditing properties and the actual primary ID), I've got a base ClassMap called AuditedEntityClassMap which is something like the following:
public class AuditedEntityClassMap<TEntity, T> : ClassMap<TEntity> where TEntity : AuditedPersistentObject<T>
{
public AuditedEntityClassMap()
{
Cache.ReadWrite();
DynamicUpdate();
ApplyId();
this.ChangeAuditInfo();
}
protected virtual void ApplyId()
{
if (typeof(T) == typeof(int))
map.Id(x => x.Id).GeneratedBy.HiLo(HiLoConstants.NHibernateHiLoTable, HiLoConstants.NHibernateHiLoColumn, HiLoConstants.NHibernateHiLoMaxLo);
else if (typeof(T) == typeof(Guid))
map.Id(x => x.Id).GeneratedBy.GuidComb();
else
throw new InvalidIdTypeInClassMappingException("Invalid type set in class mapping: " + typeof(T));
}
}
My question is that the type checking of the generic in order to determine the type of NHibernate generator mapping that should be used for it smells and I'm wondering if there's a better way of dealing with it.
开发者_JAVA百科- The generic type for my domain entities' IDs is used throughout and works great everywhere else (and it's used extensively).
- I'd prefer not to have to define the ID mapping in every entity's ClassMap if I can avoid it. If this is the only way to do so, I'll live with it.
Thoughts and suggestions?
I' could not get your code to compile, but I am surprised it works.
Wouldn't T be the DataClass instead of the id.
An other way I can thing of is with reflection but I can't imagine that to be much better way.
You could get the properties of T with reflection and search for a property named Id or id. And then get the type of that property. But I don't know how you would call Map in this context.
var pp = typeof(T).GetProperties().Where(p => p.Name == "Id").FirstOrDefault();
if (pp != null)
{
if (pp.PropertyType.Name == "Int64" || pp.PropertyType.Name == "Int32")
{
Map();
}
}
Looks like there's nothing better than what I've got now.
精彩评论