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:


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





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

Accepted Answer

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


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.

Popular Answer

An alternative to looping through your entity types is to make the entities you don't want audited implement the same interface and exclude that. For example:

public interface IExcludeFromAudit
{ }

And your entities:

public class Order : IExcludeFromAudit

And now just exclude the interface:


The benefit of this is that it's now easy to control which ones are excluded.

Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why