Get Type from EF Core Context

c# entity-framework-core

Question

I am trying to get the type of an entity from a given string. My end goal is to make an interface (UI interface) for users to have a GUI to explore my Database. They basically have a tree of tables and their fields and as they select fields, I want to build up the SQL query on the backend and return the data. I'm getting stuck on how to get the Type.

I'm trying to staple together a solution between these threads:

Here's my current attempt(s):

var type1 = _dbContext.Model.FindEntityType("Chadwick.Database.Entities.Appearances");
var type = _dbContext.Appearances.GetType();
var context = _dbContext.Set(typeof(Appearance)); // this works. I just need to pass in a variable instead of the actual type
var stuff = await context.FromSql("SELECT TOP 100 * FROM Appearances").ToListAsync();
// var data = await _dbContext.Appearances.Select(a => new {a.PlayerId}).Take(100).ToListAsync();
return new OkObjectResult(stuff);

Essentially, I will never know that they are after "Appearances", so I can't just provide the exact type, I need to fetch it (by string) from the context.

Is there a way to get the actual type by string?

I know I could do something like this, but it seems redundent (there's about 20 tables and will be more)

public Type GetTypeByName(string name)
{
    switch (name)
    {
        case "Appearances":
            return typeof(Appearance);
        case "AwardsManagers":
            return typeof(AwardsManager);
    }

    return null;
}
1
1
5/25/2019 1:28:45 AM

Accepted Answer

Basically you need to know the entity class namespace, because the name itself is not enough to uniquely identify the entity type.

Once you know that, you can obtain the EF Core metadata for that entity using the FindEntityType method like in your first attempt:

var entityType = _dbContext.Model.FindEntityType("Chadwick.Database.Entities." + className);

The result of that method is null if no such entity exists, IEntityType instance otherwise. It can be used to obtain other EF Core metadata related to the entity, like properties, navigations, table name etc. And the type of the associated class that you need is provided by the ClrType property:

var classType = entityType.ClrType;
3
5/26/2019 8:41:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow