1

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"?

MarGraz
  • 61
  • 9
  • If `DbSet` doesn't exis,you can use `context.Set()` to query – Yinqiu Dec 22 '20 at 03:21
  • @Yinqiu thank you for your answer. The problem is that context.Set() requires that "Article" class is passed directly, you can't pass it dynamically as I wish, for example: `object instantiatedObject = Activator.CreateInstance(objectType); context.Set();` – MarGraz Dec 22 '20 at 17:57

1 Answers1

1

In the end I solved using "Linq.Dynamic.Core" that allows you to use Linq and writing a lambda expression as a string, and much more, here more info about Dynamic Linq.

Here how I modified the TestMethod() showed before, and how I did the query against the "Article" table added dynamically via my "GenericContextApp" class.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
    
    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();

                IEnumerable<IEntityType> contextEntitiesList = context.Model.GetEntityTypes();
                IQueryable<IEntityType> entitiesList = contextEntitiesList.Select(p => p).ToList().AsQueryable();

                //Query against the dinamycally added "Article" table. It will return the SQL query as a string.
                result = context.Query("Your.Complete.Namespace.Article").Where("Body == \"ciao\"").ToQueryString();   

                return result;
            }
        }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MarGraz
  • 61
  • 9