【问题标题】:Get Type from EF Core Context从 EF Core 上下文中获取类型
【发布时间】:2019-05-25 01:19:19
【问题描述】:

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

我正在尝试在这些线程之间拼凑出一个解决方案:

这是我目前的尝试:

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);

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

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

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

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

    return null;
}

【问题讨论】:

  • string name 是什么意思——表名还是实体名?
  • string name 是实体名称

标签: c# entity-framework-core


【解决方案1】:

基本上你需要知道实体类namespace,因为名字本身不足以唯一标识实体类型。

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

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

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

var classType = entityType.ClrType;

【讨论】:

    猜你喜欢
    • 2017-11-25
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2021-09-28
    • 2019-02-01
    • 2022-08-21
    • 1970-01-01
    相关资源
    最近更新 更多