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 ?

1
0
4/19/2017 12:34:46 PM

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.

2
4/19/2017 12:52:27 PM

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow