简体   繁体   中英

Fluent NHibernate how to override mappings for an abstract base class

I want 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;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM