jeudi 2 février 2023

EF Core, how can I query my DbContext when I only have a string variable containing a type?

I have two string variables entityName and entityId. I also have a DbContext with many data sets. I need to query the context using the type contained in entityName and I know that its value will match the name of the type of one of those data sets at this point. Here is my current approach (issue at the end):

var type = Type.GetType(entityName);
if (type == null) throw new Exception("Cannot find Type" + entityName);
var entity = await context.Set<type>().FindAsync(entityId);

The issue is that the compiler tells me I cannot use a Type variable type as a Type itself. Which makes sense, but I'm not sure where to go from here. I have also tried context.Set(type) which also give me compiler errors.





Aucun commentaire:

Enregistrer un commentaire