lundi 13 avril 2020

C# Create function using reflection

I have a generic method which deletes many objects using SQL and marks the entities as detached (EF). Currently I pass in a list of objects and a function for fetching the primary key of the object to be included in the SqlParameters. When I tried to fetch the properties (PK) from each object with reflection rather than passing in a function it had an impact on performance for large numbers of objects.

Is it possible to use reflection on the first object to create this function, then use this function the fetch all the properties (PK) from the item in the list without using reflection?

This is an example of how the function is currently called.

Db.DeleteMany(someObjects, obj => obj.PrimaryKey);

(I'm trying to create the second parameter using reflection, without the resulting function also using reflection to fetch the value)

Though I cannot share the actual implementation (I wrote it but I do not own it) here is the signature of the deleteMany method.

public static void DeleteMany<T1, T2>(this DbContext context, List<T1> items, Func<T1, T2> getKey) where T1 : class

All the other information is such as tableName and tablePkName is fetched using reflection on the DbContext based on the type of T1. T2 is the type of the PK in the object itself.





Aucun commentaire:

Enregistrer un commentaire