Home > Mobile >  Get generic list from single EndPoint C#
Get generic list from single EndPoint C#

Time:10-01

I create a generic method for getting a generic list with EF

public async Task<IEnumerable<T>> GetLookupListAsync<T>() where T : class, IBaseLookup
{
    return await _contextDb.GetDbSet<T>().ToListAsync();
}

Then from my API, I call this method multiple times based on the type I need

[HttpGet]
[Route("title")]
public async Task<IActionResult> GetTitlePersona(DataSourceLoadOptions loadOptions)
{
    var title = await _lookupService.GetLookupListAsync<Title>();
    return Ok(DataSourceLoader.Load(title , loadOptions));
}

[HttpGet]
[Route("Test")]
public async Task<IActionResult> GetTestPersona(DataSourceLoadOptions loadOptions)
{
    var test = await _lookupService.GetLookupListAsync<Test>();
    return Ok(DataSourceLoader.Load(test, loadOptions));
}

Is there a way to create a single EndPoint, not to create N EndPoints that do the same things?

CodePudding user response:

It's possible with reflection:

[HttpGet]
[Route("GetData")]
public async Task<IActionResult> GetData(string kind, DataSourceLoadOptions loadOptions)
{
    string namespace = "namespace";
    Type type = Type.GetType($"{namespace}.{kind}");

    MethodInfo method = typeof(_lookupService).GetMethod(nameof(_lookupService.GetLookupListAsync), BindingFlags.NonPublic | BindingFlags.Instance);
    MethodInfo genericMethod = method.MakeGenericMethod(type);
    var task = (Task)genericMethod.Invoke(this);
    await task;
    var resultProperty = task.GetType().GetProperty("Result");
    var result = resultProperty.GetValue(task)
    return Ok(DataSourceLoader.Load(result, loadOptions));
}

You have to set the namespace with the namespace where 'title' and 'test' are in, and probably you will have to cast 'result' to the right type...

CodePudding user response:

one simple way is to create a method with a kind variable and have a switch for different lookups, like:

[HttpGet]
[Route("GetData")]
public async Task<IActionResult> GetData(string kind, DataSourceLoadOptions loadOptions)
{
    if (kind == "Title")
    {
        var result = await _lookupService.GetLookupListAsync<Title>();
        return Ok(DataSourceLoader.Load(result, loadOptions));
    }
    else if (kind == "Test")
    {
        var result = await _lookupService.GetLookupListAsync<Test>();
        return Ok(DataSourceLoader.Load(result, loadOptions));
    }
}
  • Related