我有一个 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
发布评论