2011-09-14 93 views
0

我想爲我所有的Types Of AuditedEntity做到這一點,但正如我們已經告訴FH忽略基本摘要,代碼沒有被擊中。我不想爲我所有的實體做到這一點,然後讓別人忘記,當他們添加新typeof<AuditedEntity>流利NHibernate如何覆蓋抽象基類的映射

public abstract class AuditedEntity : Entity ... 

public class AuditedEntityMappings : IAutoMappingOverride<AuditedEntity> 
    { 
    public void Override(AutoMapping<AuditedEntity> mapping) 
    { 
     mapping.Where("DeletedById is null"); 
    } 
    } 

This post看起來很有前途,但該方法已被棄用

回答

0

得到它的工作多虧了一些幫助一些合理導致以下擴展的複雜表達式:

var model = 
    AutoMap.AssemblyOf<AuditedEntity>(new AutomappingConfiguration(databaseName)) 
    .HideDeletedEntities(); 

... 

public static class ReflectiveEnumerator 
    { 
    public static IEnumerable<Type> GetSubTypesOf<T>() where T : class 
    { 
     return Assembly.GetAssembly(typeof (T)).GetTypes() 
     .Where(myType => myType.IsClass && 
      !myType.IsAbstract && 
      myType.IsSubclassOf(typeof (T))); 
    } 
    } 

    public static class AutoPersistenceModelExtensions 
    { 
    public static AutoPersistenceModel HideDeletedEntities(this AutoPersistenceModel model) 
    { 
     var types = ReflectiveEnumerator.GetSubTypesOf<AuditedEntity>(); 

     foreach (var t in types) 
     { 
     var mapped = typeof(AutoMapping<>).MakeGenericType(t); 

     var p = Expression.Parameter(mapped, "m"); 
     var expression = Expression.Lambda(Expression.GetActionType(mapped), 
              Expression.Call(p, mapped.GetMethod("Where"), 
                  Expression.Constant("DeletedById is null")), p); 

     typeof(AutoPersistenceModel).GetMethod("Override").MakeGenericMethod(t) 
      .Invoke(model, new object[] { expression.Compile() }); 
     } 
     return model; 
    } 
    }