【问题标题】:How to pass variable entities to a generic function?如何将变量实体传递给通用函数?
【发布时间】:2017-04-19 12:34:46
【问题描述】:

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

AuditManager.DefaultConfiguration.Exclude<T>();

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

例如:

AuditManager.DefaultConfiguration.Exclude<Employee>();

AuditManager.DefaultConfiguration.Exclude<Department>();

AuditManager.DefaultConfiguration.Exclude<Room>();

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

【问题讨论】:

  • 您没有将实体传递给泛型函数,而是将 entity-types 传递给泛型函数。
  • @Maarten:你是对的,如何创建实体类型列表并将项目传递给通用函数?
  • 这听起来像是一个 X-Y 问题,你到底想在这里实现什么?
  • @Maarten : 它尝试以下List&lt;Type&gt; types = new List&lt;Type&gt;(); types.Add(typeof(Employee)); 但不能使用types[0] 作为函数参数
  • @DavidG : 我想控制应该通过该功能排除的实体,管理员用户应该选择一组实体,我想将这些实体传递给 exclude function 以将它们排除在审计之外

标签: c# .net entity-framework generics entity-framework-plus


【解决方案1】:

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

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&lt;T&gt; 方法是DefaultConfiguration 指向的任何实例上的实例方法。

【讨论】:

    【解决方案2】:

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

    public interface IExcludeFromAudit
    { }
    

    还有你的实体:

    public class Order : IExcludeFromAudit
    {
        //snip
    }
    

    现在只排除接口:

    AuditManager.DefaultConfiguration.Exclude<IExcludeFromAudit>();
    

    这样做的好处是现在可以轻松控制排除哪些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2020-12-20
      • 2011-06-21
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多