I'm using EF Core v. 5.0 and SQLite DB and I'm trying to dynamically add a DbSet to my DbContext. I have followed and readapted this guide to EF Core: https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/ and I realized this DbContext class:
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[] { });
}
}
}
}
My "Blog" and "Article" classes:
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; }
}
And here is how I initialized the DbContext, in "tables" variable I can see the "Article" table added dynamically using 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();
}
}
At this point, I succesfully saw the "Article" class added dynamically, but I can't query "Article" using Linq, of course, because it doesn't exist fisically in the DbContext.
Is there a way to use Linq against a dynamic DbSet added table like "Article"?