EF Core 2.0中的动态访问表

EF Core 2.0中的动态访问表,第1张

EF Core 2.0中的动态访问表

首先,您需要从名称中获取实体的类型(如果您具有类型,则直接使用它即可)。您可以为此使用反射,但是EF
Core的正确方法可能是使用

FindEntityType
方法。

一旦有了类型,问题就是如何获取相应的

DbSet<T>
。EF
Core当前不提供
Set(Type)
类似于EF6的非通用方法,主要是因为没有非通用
DbSet
类。但是,你仍然可以得到相应
DbSet<T>
IQueryable
通过或者使用一些EF核心内部:

using System;using System.Linq;using Microsoft.EntityframeworkCore.Internal;namespace Microsoft.EntityframeworkCore{    public static partial class CustomExtensions    {        public static IQueryable Query(this DbContext context, string entityName) => context.Query(context.Model.FindEntityType(entityName).ClrType);        public static IQueryable Query(this DbContext context, Type entityType) => (IQueryable)((IDbSetCache)context).GetOrAddSet(context.GetDependencies().SetSource, entityType);    }}

Set<T>
通过反射调用通用方法:

using System;using System.Linq;using System.Reflection;namespace Microsoft.EntityframeworkCore{    public static partial class CustomExtensions    {        public static IQueryable Query(this DbContext context, string entityName) => context.Query(context.Model.FindEntityType(entityName).ClrType);        static readonly MethodInfo SetMethod = typeof(DbContext).GetMethod(nameof(DbContext.Set));        public static IQueryable Query(this DbContext context, Type entityType) => (IQueryable)SetMethod.MakeGenericMethod(entityType).Invoke(context, null);    }}

在这两种情况下,您都可以使用以下内容:

db.Query("Namespace.MyTable").Where(...)

要么

db.Query(typeof(MyTable)).Where(...)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5014813.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存