如何从 EF Core/.NET Core 2.0 中的实体名称获取 DbSet [英] How to get DbSet from entity name in EF Core / .NET Core 2.0
问题描述
我有一个 DbContext
和几个 DbSet
属性:
I have a DbContext
with several DbSet<T>
properties:
public virtual DbSet<A> A { get; set; }
public virtual DbSet<B> B { get; set; }
public virtual DbSet<C> C { get; set; }
...
在某些情况下,我现在必须能够检索实体名称作为字符串的特定 DbSet(例如,当用户输入A"时,我需要获取 Dbset
).
In certain scenarios I must now be able to retrieve a specific DbSet with the entity name as string (e.g. when the user enters "A", I need to get the Dbset<A>
).
在以前的 EF 版本中,以下是可能的:
In previous EF versions, the following was possible:
var dbset = Context.Set(Type.GetType(A));
当前版本的 EF 核心是否有类似的方法?我已经尝试了几种方法来实现这一点,但目前我让它工作的唯一方法是使用一个相当丑陋的开关/外壳,我想摆脱它.
Is there a similar way to do so with the current versions of EF core? I've tried several ways to achieve that, but the only way I have it working at the moment is using a rather ugly switch/case and I would like to get rid of that.
我在这里发现了几篇有类似问题的帖子,但它们都与早期的 .NET Core 版本或 EF5/EF6 相关.
I've found several posts with similar issues around here, but all of them relate to early .NET Core versions or EF5 / EF6.
推荐答案
这样做是为了在 de dbcontext 类中添加 de extension Set(Type t) 方法.
Do this to add de extension Set(Type t) method to de dbcontext class.
using Microsoft.EntityFrameworkCore;
namespace ApiWebApplication.Utils
{
public static class MyExtensions
{
public static IQueryable<object> Set (this DbContext _context, Type t)
{
return (IQueryable<object>)_context.GetType().GetMethod("Set").MakeGenericMethod(t).Invoke(_context, null);
}
}
}
示例:
// GET: api/Employees
[HttpGet]
public IEnumerable<object> GetEmployees()
{
return _context.Set(typeof(Employee));
}
这篇关于如何从 EF Core/.NET Core 2.0 中的实体名称获取 DbSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!