Entity Framework Core 中的动态 DbSet [英] Dynamic DbSet in Entity Framework Core

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

问题描述

string tableName = "TblStudents";
Dictionary<string, Type> myDictionary = new Dictionary<string, Type>()
{
    { "TblStudents", typeof(TblStudent) },
    { "TblTeachers", typeof(TblTeacher) }
};

// Context always same
DBContext dbContext = new DBContext();
DbSet dbSet = dbContext.Set(myDictionary[tableName]);

以上代码来自这个 发布 我可以动态DbSet 的地方.我怎样才能在 Entity Framework Core 中做到这一点?

Above code is from this post where I can DbSet dynamically. How can I make this work in Entity Framework Core?

我在

DbSet dbSet = dbContext.Set(myDictionary[tableName]);

似乎在新版本中更改了 Set 方法.

seems like Set method has been changed in the new version.

感谢帮助.

推荐答案

如果您尝试通过 TEntity 获取 DbSet,请使用:>

If you're trying to get the DbSet<TEntity> by TEntity, use:

var dbSet = dbContext.Set<TEntity>();

如果您想根据字符串名称和字典调用该方法,则必须使用反射.

If you want to call that method based off a string name and your dictionary, you'll have to use reflection.

EF Core 似乎没有非通用的 DbSet,因此您必须使用非通用接口之一,例如 IQueryable,我会包括一个 Func,如果您坚持使用字典映射路线,您可以调用它来获取 IQueryable 而不仅仅是类型.例如:

EF Core does not appear to have a non-generic DbSet so you'll have to use one of the non-generic interfaces such as IQueryable and I'd include a Func that you can invoke to get the IQueryable instead of just the type if you insist on going the dictionary mapping route. For example:

var myDictionary = new Dictionary<string, Func<DbContext, IQueryable>>()
{
    { "TblStudents", ( DbContext context ) => context.Set<TblStudent>() }
};

var dbSet = myDictionary[ "TblStudents" ].Invoke( dbContext );

这篇关于Entity Framework Core 中的动态 DbSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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