c# - 动态获取一个 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();
}
解决方案
推荐阅读
- django - Django 与 BeautifulSoup 的 lxml 解析器的兼容性
- javascript - 如何使用codemirror显示像mozilla开发网络一样的代码输出?
- css - CSS @keyframes 动画在悬停时不断闪烁
- encryption - 如何使用 Virgil 安全加密和解密消息?
- google-app-engine - 谷歌应用引擎项目多区域部署
- angular - 我们如何在 Angular 4 应用程序中为特定的 html 页面导入条件 css 文件?
- android - 更改系统语言时,Android 复数无法正常工作
- scala - 如何在 Play 自己的代码中使用 Status
- javascript - javascript中的mouseChildren之类的东西
- spring - Spring Security - 从本地调用安全方法