EF Core 2.0 中的动态访问表 [英] Dynamically access table in EF Core 2.0
问题描述
我正在使用 System.Linq.Dynamic.Core
将 lambda 表达式动态添加到 EF 中的查询中.
I am using System.Linq.Dynamic.Core
to dynamically add in lambda expressions to queries in EF.
我还希望能够按名称选择表格.我找到了这个答案:
I want to also be able to select the table by name. I found this answer:
https://stackoverflow.com/a/28101268/657477
但它不适用于 asp.net core 2.0.我不能使用 DbSet
我必须使用 DbSet
它在错误消息中说.
But it is not working in asp.net core 2.0. I cannot use DbSet
I must use DbSet<TEntity>
it says in error message.
我希望能够做到 db.GetTable("Namespace.MyTable").Where(...)
我该怎么做?
推荐答案
首先需要从名称中获取实体的类型(如果有类型,直接使用即可).您可以为此使用反射,但 EF Core 的正确方法可能是使用 FindEntityType
方法.
First you need to get the type of the entity from the name (in case you have the type, just use it directly). You can use reflection for that, but probably the correct way for EF Core is to use FindEntityType
method.
一旦有了类型,问题就是如何得到对应的DbSet
.EF Core 目前没有提供类似于 EF6 的非通用 Set(Type)
方法,主要是因为没有非通用的 DbSet
类.但是你仍然可以通过使用一些 EF Core 内部来获得相应的 DbSet
作为 IQueryable
:
Once you have the type, the problem is how to get the corresponding DbSet<T>
. EF Core currently does not provide non generic Set(Type)
method similar to EF6, mainly because there is no non generic DbSet
class. But you can still get the corresponding DbSet<T>
as IQueryable
by either using some EF Core internals:
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
方法:
or invoking the generic Set<T>
method via reflection:
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);
}
}
在这两种情况下,您都可以使用以下内容:
In both cases you can use something like this:
db.Query("Namespace.MyTable").Where(...)
或
db.Query(typeof(MyTable)).Where(...)
这篇关于EF Core 2.0 中的动态访问表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!