首页 > 解决方案 > 动态获取一个 DbSet按实体类名称 - EF Core

问题描述

这已经被问过并回答过,但对于.Net Framework。我正在努力在 .Net Core 中实现相同的功能。

我有一个接收实体名称作为字符串的方法(以及一些选择标准)。我想使用 entityName 字符串获取实体类型并查询 EF。

使用 EF 6 的先前答案建议如下

public async Task<bool> MyMethod(string _type)
{
    Type type = Type.GetType(_type);

    var tableSet = _context.Set(type);

    var list = await db.ToListAsync();

    // do something
}

// pass the full namespace of class
var result = await MyMethod("Namespace.Models.MyClass")

不幸的是context.Set不再接受参数,所以这是不可能的。

我尝试了几种方法来获取和使用带有上下文的类型,但我遇到了障碍。我将在这里转储测试代码 - 但这些都没有达到我想要的。

public IList LoadByKey(string entityName, params string[] parameters)
{
    // Get type from entity name string - Include assembly
    Type clType = Type.GetType($"{entityName},Savant.Pulse.Testbeds.ReferenceData.DB");

    // Create instance using the type retrieved from GetType, still just an Object
    var instantiatedObject = Activator.CreateInstance(clType);

    // Get the entity type from the context itself.  This does return the correct type.
    // So I thought I was heading in the correct direction.
    var entityType = _context.Model.FindEntityType(entityName);

    // Get a DbSet of the correct type.  Once again this does return what you think you'd need. 
    // But it's an Object? type returned.  I can't seem to cast it to the correct type from the entityName. 
    var dbSet = _context.GetType().GetProperty(entityType.ClrType.Name).GetValue(_context);

    throw new System.NotImplementedException();
}

标签: c#.net-coreentity-framework-core

解决方案


推荐阅读