dimanche 18 août 2019

How to pass an string as a type parameter for a generic DbSet in Entity Framework?

Consider the following sample code, What's the most concise way to pass C# generic type as a parameter?

public dynamic MyDbSet(string typeName)
{
    var typeofDbSet = typeof(DbSet<>);
    Type[] typeArgs = { Type.GetType(typeName) };
    var type = typeofDbSet.MakeGenericType(typeArgs);
    dynamic dbsetOfT = Activator.CreateInstance(type);

    return dbsetOfT;

    //Call it
    //var notificationTypes = MyDbSet("NotificationType");
    //var list = notificationTypes.ToList();
}

Or something like this:

public dynamic MyDbSet2(string typeName)
{
    var keyValuePairs = new Dictionary<string, dynamic>
    {
        {nameof(NotificationType), Set<NotificationType>().AsQueryable()}
    };

    return keyValuePairs[typeName];
    //Call it
    //var notificationTypes = MyDbSet2("NotificationType");
    //var list = notificationTypes.ToList();
}





Aucun commentaire:

Enregistrer un commentaire