0

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.

scorch855
  • 302
  • 1
  • 9
  • Can you share the implementation of `DeleteMany`? Especially the portion that has the performance issue. – John Wu Apr 14 '20 at 00:40
  • Since you cache reflection results per type it's generally not a huge deal to have many objects... In addition to what @JohnWu said can you please clarify if all those objects have different types (where nothing really going to help)? Also what is type of `o=>o.PrimiaryKey` - I assume expression (and not `Func`). – Alexei Levenkov Apr 14 '20 at 00:45
  • Using [this](https://stackoverflow.com/questions/12835926/get-key-property-from-viewmodel?noredirect=1&lq=1) as a reference, it seems like you can use the [key] attribute to find your pk, then use the property name for all subsequent objects. – Jeff Apr 14 '20 at 00:45
  • I have added additional information where I can. Thanks – scorch855 Apr 14 '20 at 00:56
  • Also I should clarify, that when I say "it had an impact on performance" it's probably not enough to be considered a performance issue, just not as good as the function defined at compilation. I was hoping to bring the two closer together by only making a single call using reflection, otherwise passing in the function is not really a big deal. The other half is that I'm just quite curious if this is even possible. – scorch855 Apr 14 '20 at 01:15

0 Answers0