栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

EF Core 2.0中的动态访问表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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(...)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/405354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号