流畅的NHibernate如何覆盖抽象基类的映射

时间:2011-09-14 13:06:49

标签: c# abstract-class fluent-nhibernate-mapping

我想为我的所有Types Of AuditedEntity执行此操作,但由于我们已告知FH忽略基础摘要,因此代码不会受到影响。我不想为我的所有实体执行此操作,然后让他们在添加新typeof<AuditedEntity>

时忘记
public abstract class AuditedEntity : Entity ...

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

This post看起来很有希望,但该方法已被弃用

1 个答案:

答案 0 :(得分: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;
    }
  }