如何从 EF Core/.NET Core 2.0 中的实体名称获取 DbSet

编程入门 行业动态 更新时间:2024-10-24 16:31:41
本文介绍了如何从 EF Core/.NET Core 2.0 中的实体名称获取 DbSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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

本文发布于:2023-11-14 09:12:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586810.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   名称   Core   EF   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!