Search code examples
c#.netentity-frameworkgenericsentity-framework-plus

How to pass variable entities to a generic function?


If i generate my entities through Entity Framework Database First, and i want to use a function like that:

AuditManager.DefaultConfiguration.Exclude<T>();

considering that the number of times i want to call it should be equal to the number of entities

ex:

AuditManager.DefaultConfiguration.Exclude<Employee>();

AuditManager.DefaultConfiguration.Exclude<Department>();

AuditManager.DefaultConfiguration.Exclude<Room>();

Now how to Loop through selected number of entities and pass every one to the Exclude function ?


Solution

  • The obvious solution would be to call the method for every entity-type you want to hide. Like this:

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

    You can add conditional statements (ifs) around them to do it dynamically.

    Howevery, if you want a fully flexible solution, where you call the Exclude method based on metadata, you need something else. Something like this:

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

    This assumes that the Exclude<T> method is an instance method on whatever instance DefaultConfiguration points to.