如何从实体代理类型中获取实体 POCO 类型?

Sam*_*Axe 4 c# entity-framework-core

我正在将一个项目从 EF6 迁移到 EF-Core。元数据 API 发生了重大变化,我无法找到解决方案:

在 EF6 下,我可以使用以下方法从代理类型中找到 POCO 类型:

ObjectContext.GetObjectType(theEntity.GetType)
Run Code Online (Sandbox Code Playgroud)

但是,这在 EF-Core(无ObjectContext类)下不起作用。我搜索并搜索无济于事。有谁知道如何从 theentity或 the获取 POCO 类型entity proxy type

Mar*_*mro 7

没有完美的方法。例如,您可以检查命名空间。如果是代理,它会

private Type Unproxy(Type type)
{
    if(type.Namespace == "Castle.Proxies")
    {
        return type.BaseType;
    }
    return type;
}
Run Code Online (Sandbox Code Playgroud)


nat*_*ter 5

EF Core 不支持ObjectContextAPI。此外,EF Core 没有代理类型。

您可以从IModel.

using (var db = new MyDbContext())
{
    // gets the metadata about all entity types
    IEnumerable<IEntityType> entityTypes = db.Model.GetEntityTypes();

    foreach (var entityType in entityTypes)
    {
        Type pocoType = entityType.ClrType;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在 EF Core 2.1 中添加了延迟加载,它像在 EF6 中一样工作 - 它创建代理 - 因此 `entity.GetType()` 不会返回实体的类型,而是返回代理。这个答案不再正确。 (6认同)