开发者

Fluent NHibernate how to override mappings for an abstract base class

I wan开发者_如何学Got to do this for all my Types Of AuditedEntity, but as we've told FH to ignore base abstracts, the code isnt getting hit. i dont want to do this for all my entities and then have someone forget when they add a new 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 looked promising but that method is deprecated


Got it working thanks to some help on some reasonably complex expressions leading to the following extensions:

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;
    }
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜