【发布时间】:2020-12-21 22:26:20
【问题描述】:
我正在使用 EF Core v. 5.0 和 SQLite DB,我正在尝试将 DbSet 动态添加到我的 DbContext。我已经按照并重新改编了本指南以适应 EF Core:https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/,并且我意识到了这个 DbContext 类:
internal class GenericAppContext : DbContext
{
public GenericAppContext()
{
//Disable the EF cache system to execute every running the OnModelCreating method.
//ATTENTION: This is a performance loss action!
this.ChangeTracker.LazyLoadingEnabled = false;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
//if "bin" is present, remove all the exceeding path starting from "bin" word
if (baseDir.Contains("bin"))
{
int index = baseDir.IndexOf("bin");
baseDir = baseDir.Substring(0, index);
}
options.UseSqlite($"Data Source={baseDir}Database\\TestSQLite.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
MethodInfo addMethod = typeof(ModelBuilder).GetMethods().First(e => e.Name == "Entity");
foreach (var assembly in AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a.GetName().Name != "EntityFramework"))
{
IEnumerable<Type> configTypes = assembly
.GetTypes()
.Where(t => t.BaseType != null
&& t.BaseType.IsGenericType
&& t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in configTypes)
{
Type entityType = type.BaseType.GetGenericArguments().Single();
object entityConfig = assembly.CreateInstance(type.FullName);
addMethod?.MakeGenericMethod(entityType)
.Invoke(modelBuilder, new object[] { });
}
}
}
}
我的“博客”和“文章”类:
internal class Blog : EntityTypeConfiguration<Blog>
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
}
internal class Article : EntityTypeConfiguration<Article>
{
[Key]
public int Id { get; set; }
public string Body { get; set; }
}
这是我初始化 DbContext 的方式,在“tables”变量中,我可以看到使用 context.Model.GetRelationalModel().Tables.ToList( )
public static string TestMethod()
{
using (var context = new GenericAppContext())
{
string result = string.Empty;
//Ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created.
context.Database.EnsureCreated();
List<ITable> tables = context.Model.GetRelationalModel().Tables.ToList();
}
}
至此,成功看到动态添加的“Article”类,但是使用Linq无法查询“Article”,当然,因为它在DbContext中并不存在.
有没有办法对动态 DbSet 添加的表(如“Article”)使用 Linq?
【问题讨论】:
-
如果
DbSet不存在,可以使用context.Set<Entity>()查询 -
@Yinqiu 谢谢你的回答。问题是 context.Set
() 要求直接传递“Article”类,不能如我所愿动态传递,例如: object instantiatedObject = Activator.CreateInstance(objectType); context.Set<instantiatedObject>();
标签: .net-core entity-framework-core linq-to-entities dbset