EF Core 2.0中的动态访问表 [英] Dynamically access table in EF Core 2.0

查看:406
本文介绍了EF Core 2.0中的动态访问表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用System.Linq.Dynamic.Core为EF中的查询动态添加lambda表达式.

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<TEntity>它在错误消息中说.

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来说,正确的方法可能是使用

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<T>上. EF Core当前不提供类似于EF6的非通用Set(Type)方法,主要是因为没有非通用DbSet类.但是您仍然可以通过使用某些EF Core内部组件来获得与IQueryable相对应的DbSet<T>:

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<T>方法:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆