小编典典

EF Core 2.0中的动态访问表

c#

System.Linq.Dynamic.Core用来动态地将lambda表达式添加到EF中的查询中。

我还希望能够通过名称选择表格。我找到了这个答案:

https://stackoverflow.com/a/28101268/657477

但是它在asp.net core 2.0中不起作用。我不能使用DbSet我必须使用DbSet<TEntity>它在错误消息中说。

我想能够做 db.GetTable("Namespace.MyTable").Where(...)

我怎样才能做到这一点?


阅读 1312

收藏
2020-05-19

共1个答案

小编典典

首先,您需要从名称中获取实体的类型(如果您具有类型,则直接使用它即可)。您可以为此使用反射,但是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(...)
2020-05-19