如何根据表名在 DbContext 中选择正确的 DbSet [英] How do I select correct DbSet in DbContext based on table name

查看:34
本文介绍了如何根据表名在 DbContext 中选择正确的 DbSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有以下 DbSet 的 DbContext

Say I have a DbContext with the following DbSets

class Amimals : DbContext
{
    public DbSet<Dog> Dogs { get; set; }
    public DbSet<Cat> Cats { get; set; }
}

在每个 EntityTypeConfiguration 我为每个 DbSet 定义表

Inside of each EntityTypeConfiguration I am defining the table for each DbSet like

class DogConfig : EntityTypeConfiguration
{
    public DogConfig()
    {
        this.ToTable("DOG_TABLE");
        ...
    }
}

现在,如果我有表名和 DbContext,我该如何获取和使用正确的 DbSet?

Now, if I have the table name and the DbContext, how can I grab and use the correct DbSet?

void foo()
{
    string tableName = this.GetTableName();
    using(Animals context = new Animals())
    {
        /* Made up solution */
        DbSet animalContext = context.Where(c => c.TableName == tableName);
        ...
        /* Do something with DbSet */
        ...
    }
}

推荐答案

您可以使用 DbContext.Set(Type entityType) 方法通过 Type 从 DbContext 获取 DbSet.因此,如果您将模型类名称作为字符串,您应该对实际 clr 类型进行一些映射.

You can get DbSet from DbContext by Type using the method DbContext.Set(Type entityType). So if you have the model class name as string you should do some mapping to actual clr type.

例如:

string tableName = "Cat";
var type = Assembly.GetExecutingAssembly()
        .GetTypes()
        .FirstOrDefault(t => t.Name == tableName);

DbSet catContent;
if(type != null)
    catContext = context.Set(type);

您还可以使用完整程序集限定名称 Type.GetType(' ... ') 从字符串中获取类型

You also can get type from string using Full Assembly Qualified Name Type.GetType(' ... ')

如果你能以某种方式以通用方式存储配置并使用通用的 context.Set() 方法会更容易.

If will be even easier if you can store configurations somehow in generic way and use the generic context.Set<T>() method.

这篇关于如何根据表名在 DbContext 中选择正确的 DbSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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