C
C#

Converting from a string to a generic method invocation

Converting from a string to a generic method invocation

Ddreadfullydistinct11/21/2023
Looking for design patterns to help solve this problem I’m having at work. The situation is that we have a URL like GET /entities/<userid>/<entity type> where entity type is a string, and we want to fetch the entities of that type belonging to the current user. Normally I would just use a switch case to go from eg entitytype = “someentity” => entitiesService.GetEntities<SomeEntity>(). But my tech lead insists that new entity types should be automatically supported without code changes to this endpoint because he thinks it will be forgotten. I’ve landed on a solution using reflection to grab the types deriving from my base Entity class and build a dict of (string, Type), then using reflection to get the method info of GetEntities and use MakeGenericMethod with the type from the dict, but am not too pleased with it. I’m considering the following alternatives: - source generators, seemed like a lot of code to generate 1 switch case - using reflection in the testing to make the pipeline fail if another dev forgets to update the endpoint But I’d like to know if there are any other solutions people can think of / thoughts on some of the existing options
DDharmang11/21/2023
One question, do you use ef core? cause i recently had to change the efcore code to dapper queries as dynamic Entities are not supported. if its a local c# entity then all good
Ddreadfullydistinct11/21/2023
Yeah we use ef core But I’m using .Set<TEntity> to accomplish the generic ness
Ddont11/21/2023
so it's a table per type situation?
Ddreadfullydistinct11/21/2023
Yeah Kinda leaning towards a Dictionary<string, Func<…> that I just manually define And then an automated test that uses reflection
DDharmang11/21/2023
its a simple approach where you dont use switch case 😄 switch statement needs compiled value and not a generated one. you can use and enum. I have used it before and it works well. sharing one sample enum which maps to strings.
using Microsoft.Kiota.Abstractions.Extensions;

namespace YOURNAMESPACE
{
public class LookupEnum
{
public static LookupEnum States { get; } = new LookupEnum(9, nameof(States).ToFirstCharacterLowerCase()!);
public static LookupEnum Clients { get; } = new LookupEnum(10, nameof(Clients).ToFirstCharacterLowerCase()!);

public string Name { get; private set; }
public int Value { get; private set; }

private LookupEnum(int val, string name)
{
Value = val;
Name = name;
}

public static IEnumerable<LookupEnum> List()
{
return new[]
{
States,
Clients
};
}

public static LookupEnum? FromString(string values)
{
try
{
return List().Single(r => string.Equals(r.Name, values, StringComparison.OrdinalIgnoreCase));
}
catch
{
return null;
}
}

public static LookupEnum FromValue(int value)
{
return List().Single(r => r.Value == value);
}

public static IEnumerable<LookupEnum> FromStrings(string[] values)
{
return values.Select(FromString).Where(value => value != null)!;
}
}
}
using Microsoft.Kiota.Abstractions.Extensions;

namespace YOURNAMESPACE
{
public class LookupEnum
{
public static LookupEnum States { get; } = new LookupEnum(9, nameof(States).ToFirstCharacterLowerCase()!);
public static LookupEnum Clients { get; } = new LookupEnum(10, nameof(Clients).ToFirstCharacterLowerCase()!);

public string Name { get; private set; }
public int Value { get; private set; }

private LookupEnum(int val, string name)
{
Value = val;
Name = name;
}

public static IEnumerable<LookupEnum> List()
{
return new[]
{
States,
Clients
};
}

public static LookupEnum? FromString(string values)
{
try
{
return List().Single(r => string.Equals(r.Name, values, StringComparison.OrdinalIgnoreCase));
}
catch
{
return null;
}
}

public static LookupEnum FromValue(int value)
{
return List().Single(r => r.Value == value);
}

public static IEnumerable<LookupEnum> FromStrings(string[] values)
{
return values.Select(FromString).Where(value => value != null)!;
}
}
}
Obtained from an article by Steve (you might know him from Ardalis Endpoints) then you use if else statements, along with LookupEnum.FromString(entity) and you can also put validations if the mapping fails

Looking for more? Join the community!

C
C#

Converting from a string to a generic method invocation

Join Server
Want results from more Discord servers?
Add your server
Recommended Posts
Auto refresh inside windows formTeam , We are using windows form c#. Is there any library for auto refresh (need to few logic eve✅ Fresh Install of Windows, I'm Getting Weird Errors (NETSDK1/NU1012, and DEP0700)Anyone know what might be happening here in my Maui Blazor Hybrid projects? For the older project object reference not set to instance of object on a static method callso im trying to use an opengl binding package (Veldrid.OpenGLBinding) but, when i call any of the meWeb API model classesI'm coding a webshop using ASP.NET Core Web API for the backend and Next.js for the frontend. I'm deInvalidate JWT-Tokens on logout and password change.I have an ASP.net Web api that handles user interaction. For authentification I use JWT Tokens. I reDynamically enable/disable a route in ASP.NET 7?Is there a way to dynamically enable/disable a route in ASP.NET 7? I'd like to be able to enable/dis✅ I keep getting Error CS5001 and CS0028, how do i get rid of themin CS5001 it says Program does not contain a static "Main" method suitable for an entry point and inStruct with explicit layoutHi, I am using Wintab and I am trying to make packet struct, but I have some problem. In some situatExtending custom WPF controlWhat are my options to extend this TimePicker list element to full height that shows all items? I'm Discord.Net + MagicOnion, hehehHey! So I am working on a discord bot that I want to intergrate into a server using websockets, I fA question for my c# winforms projecthello guys, i have a question about my c# winforms project. So : I have 2 Projects the first ProjecYO I NEED HELP writing a code need advice not for u to write it for mewrite me a c# program that get 3 latters and tell if they are by the order like abc if they are backBlazor ServicesI dont know too much blazor, but I have a .cs file in a /Settings folder, in which I would like to aHow to optimize this?I have following: ```cs using System; namespace SquareCalculus { internal class FigureTriangle In VSCode, SDK not Recognized on ChromeOSHi. I just installed the .NET SDK and the Runtime by following the instructions for Ubuntu on the MiNito.AsyncEx vs DotNext.ThreadingWe're currently searching for a nice AsyncAutoResetEvent implementation. We found two suitable impleSequential BlinkersHello everyone! I bought these sequential blinkers that run off an stm32 blue pill board. the only pTrying to use Microsoft.Kiota namespace but not found when importingI am trying to use this method from the Microsoft.Kiota.Abstractions.Extensions namespace: ToFirstChWinUI3 Scheduler CalendarViewhello im trying to make a winui3 calendarview interactive calendar where I can predefine dates in myThe call is ambiguous between the following methods or properties: 'Thread.Thread(ThreadStart)' andi have to upload by files