0

我想为我的所有Types Of AuditedEntity. 我不想为我的所有实体都这样做,然后让某人在添加新实体时忘记typeof<AuditedEntity>

public abstract class AuditedEntity : Entity ...

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

这篇文章看起来很有希望,但该方法已被弃用

4

1 回答 1

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;
    }
  }
于 2011-09-22T09:08:09.550 回答