0

如果我通过Entity Framework Database First生成我的实体,并且我想使用这样的函数:

AuditManager.DefaultConfiguration.Exclude<T>();

考虑到我想调用它的次数应该等于实体的数量

前任:

AuditManager.DefaultConfiguration.Exclude<Employee>();

AuditManager.DefaultConfiguration.Exclude<Department>();

AuditManager.DefaultConfiguration.Exclude<Room>();

现在如何遍历选定数量的实体并将每个实体传递给Exclude函数?

4

2 回答 2

2

显而易见的解决方案是为您要隐藏的每个实体类型调用该方法。像这样:

AuditManager.DefaultConfiguration.Exclude<Employee>();
AuditManager.DefaultConfiguration.Exclude<Department>();
AuditManager.DefaultConfiguration.Exclude<Room>();

您可以在它们周围添加条件语句 ( ifs) 以动态执行此操作。

但是,如果您想要一个完全灵活的解决方案,在其中调用Exclude基于元数据的方法,则需要其他东西。像这样的东西:

var types = new[] { typeof(Employee), typeof(Department), typeof(Room) };
var instance = AuditManager.DefaultConfiguration;
var openGenericMethod = instance.GetType().GetMethod("Exclude");
foreach (var @type in types)
{
    var closedGenericMethod = openGenericMethod.MakeGenericMethod(@type);
    closedGenericMethod.Invoke(instance, null);
}

这假定该Exclude<T>方法是任何实例DefaultConfiguration指向的实例方法。

于 2017-04-19T12:52:27.383 回答
2

循环遍历实体类型的另一种方法是使您不想审计的实体实现相同的接口并将其排除。例如:

public interface IExcludeFromAudit
{ }

和您的实体:

public class Order : IExcludeFromAudit
{
    //snip
}

现在只排除接口:

AuditManager.DefaultConfiguration.Exclude<IExcludeFromAudit>();

这样做的好处是现在很容易控制哪些被排除在外。

于 2017-04-19T12:58:35.127 回答