如何从EF Core / .NET Core 2.0中的实体名称获取DbSet [英] How to get DbSet from entity name in EF Core / .NET Core 2.0
问题描述
我有一个 DbContext
,其中有几个 DbSet< T>
属性:
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< A>
)。
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 Extension Set(Type t)方法添加到dbcontext类。
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屋!