【发布时间】:2020-11-22 20:15:12
【问题描述】:
如何获取 Entity Framework Core DBSet,其中输入是字符串变量名?尝试获取下面的 DBSet 类型,但改为接收 IQueryable。
上一个答案在 Net Core 3.0 中不起作用
资源:Getting DbSet<MyTable> from a string
How do I select correct DbSet in DbContext based on table name
var tableString = "Product";
var tableType = Type.GetType(tableString, false, true);
if (tableType == null)
{
throw new ArgumentException($"Invalid table type: {tableType }.");
}
_dbContext.Set<Product>().Add({ProductId = 5, ProductName = "Furniture"}); // Adding to a DbSet, This will work !
_dbContext.Set(tableType).Add({ProductId = 5, ProductName = "Furniture"}); // Cannot add to this, since this is actually an IQueryable
错误:“IQueryable”不包含“Add”的定义,并且找不到接受“IQueryable”类型的第一个参数的可访问扩展方法“Add”(您是否缺少 using 指令或程序集引用?)
【问题讨论】:
标签: c# entity-framework asp.net-core .net-core entity-framework-core