How to pass variable entities to a generic function?

.net c# entity-framework entity-framework-plus generics

Question

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 ?

Accepted Answer

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.


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
{
    //snip
}

And now just exclude the interface:

AuditManager.DefaultConfiguration.Exclude<IExcludeFromAudit>();

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




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