从 EF Core 上下文获取类型

mwi*_*son 1 c# entity-framework-core

我正在尝试type从给定的字符串中获取实体的 。我的最终目标是为用户制作一个界面(UI 界面),让用户有一个 GUI 来探索我的数据库。他们基本上有一个表及其字段的树,当他们选择字段时,我想在后端建立 SQL 查询并返回数据。我被困在如何获得类型上。

我正在尝试将这些线程之间的解决方案钉在一起:

这是我目前的尝试:

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);
Run Code Online (Sandbox Code Playgroud)

本质上,我永远不会知道它们是在“外观”之后,所以我不能只提供确切的类型,我需要从上下文中(通过字符串)获取它。

有没有办法通过字符串获取实际类型?

我知道我可以做这样的事情,但它似乎是多余的(大约有 20 张桌子,而且还会更多)

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

    return null;
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*oev 5

基本上你需要知道实体类的命名空间,因为名称本身不足以唯一标识实体类型。

知道这一点后,您可以使用FindEntityType第一次尝试中的方法获取该实体的 EF Core 元数据:

var entityType = _dbContext.Model.FindEntityType("Chadwick.Database.Entities." + className);
Run Code Online (Sandbox Code Playgroud)

该方法的结果是null如果不存在这样的实体,则IEntityType实例否则。它可用于获取与实体相关的其他 EF Core 元数据,如属性、导航、表名等。您需要的关联类的类型由ClrType属性提供:

var classType = entityType.ClrType;
Run Code Online (Sandbox Code Playgroud)