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

查看:277
本文介绍了如何根据表名称在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);

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

您还可以使用完整程序集合格名称Type.GetType('...')

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

如果您可以某种方式以通用方式存储配置并使用通用context.Set<T>()方法,将会更加容易.

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天全站免登陆