Dynamically create Entity,DbSet,Migration file,Migrator file and Tables

I want to dynamically generate the following components based on user input properties:

Entity Class: Create a C# class representing the entity with properties based on user input.
DbSet: Add a DbSet property to the DbContext for the newly created entity.
Migration File: Generate a migration file that includes the necessary schema changes for the new entity.
Migrator File: Implement a migrator to handle the migration process and ensure the database schema is updated accordingly.
The properties for the new entity will be specified in a dictionary like this:

var properties = new Dictionary<string, Type>
{
    { "Name", typeof(string) },
    { "CreatedDate", typeof(DateTime) }
};

Using this dictionary, the system should:

Create an entity class with properties matching the dictionary entries.
Update the DbContext to include a DbSet for the new entity.
Generate a migration file that reflects the schema changes for the new entity.
Apply the migration to the database to ensure that the table is created or updated with the specified columns.

While I tried using this code

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

public static class DynamicTypeBuilder
{
    public static Type CreateDynamicType(string className, Dictionary<string, Type> properties)
    {
        var typeBuilder = GetTypeBuilder(className);
        foreach (var property in properties)
        {
            CreateProperty(typeBuilder, property.Key, property.Value);
        }
        return typeBuilder.CreateTypeInfo().AsType();
    }

    private static TypeBuilder GetTypeBuilder(string className)
    {
        var assemblyName = new AssemblyName(className);
        var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
        return moduleBuilder.DefineType(className, TypeAttributes.Public | TypeAttributes.Class);
    }

    private static void CreateProperty(TypeBuilder typeBuilder, string propertyName, Type propertyType)
    {
        var fieldBuilder = typeBuilder.DefineField($"_{propertyName}", propertyType, FieldAttributes.Private);
        var propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

        var getterMethod = typeBuilder.DefineMethod($"get_{propertyName}", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
        var getterIl = getterMethod.GetILGenerator();
        getterIl.Emit(OpCodes.Ldarg_0);
        getterIl.Emit(OpCodes.Ldfld, fieldBuilder);
        getterIl.Emit(OpCodes.Ret);

        var setterMethod = typeBuilder.DefineMethod($"set_{propertyName}", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { propertyType });
        var setterIl = setterMethod.GetILGenerator();
        setterIl.Emit(OpCodes.Ldarg_0);
        setterIl.Emit(OpCodes.Ldarg_1);
        setterIl.Emit(OpCodes.Stfld, fieldBuilder);
        setterIl.Emit(OpCodes.Ret);

        propertyBuilder.SetGetMethod(getterMethod);
        propertyBuilder.SetSetMethod(setterMethod);
    }
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Collections.Generic;

public class DynamicDbContext : DbContext
{
    private readonly IEnumerable<Type> _entityTypes;

    public DynamicDbContext(DbContextOptions<DynamicDbContext> options, IEnumerable<Type> entityTypes)
        : base(options)
    {
        _entityTypes = entityTypes;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entityType in _entityTypes)
        {
            modelBuilder.Model.AddEntityType(entityType);
        }

        base.OnModelCreating(modelBuilder);
    }
}

public class DynamicModelCustomizer : ModelCustomizer
{
    private readonly IEnumerable<Type> _entityTypes;

    public DynamicModelCustomizer(ModelCustomizerDependencies dependencies, IEnumerable<Type> entityTypes)
        : base(dependencies)
    {
        _entityTypes = entityTypes;
    }

    public override void Customize(ModelBuilder modelBuilder, DbContext context)
    {
        foreach (var entityType in _entityTypes)
        {
            modelBuilder.Model.AddEntityType(entityType);
        }

        base.Customize(modelBuilder, context);
    }
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using System.Threading.Tasks;

public class MigrationService
{
    private readonly IMigrator _migrator;
    private readonly DynamicDbContext _context;

    public MigrationService(IMigrator migrator, DynamicDbContext context)
    {
        _migrator = migrator;
        _context = context;
    }

    public void Migrate()
    {
        _context.Database.Migrate();
    }

    public async Task ApplyMigrationsAsync()
    {
        var pendingMigrations = await _context.Database.GetPendingMigrationsAsync();
        foreach (var migration in pendingMigrations)
        {
            await _migrator.MigrateAsync(migration);
        }
    }
}
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        var serviceProvider = serviceCollection.BuildServiceProvider();
        using (var scope = serviceProvider.CreateScope())
        {
            var migrationService = scope.ServiceProvider.GetRequiredService<MigrationService>();
            migrationService.Migrate();
            await migrationService.ApplyMigrationsAsync();

            // Insert data to test if tables are created and functioning
            var context = scope.ServiceProvider.GetRequiredService<DynamicDbContext>();
            InsertTestData(context);
        }
    }

    private static void ConfigureServices(IServiceCollection services)
    {
        var entityTypes = new List<Type>();

        // Define dynamic entities
        var dynamicEntities = GetDynamicEntities();

        foreach (var entity in dynamicEntities)
        {
            var type = DynamicTypeBuilder.CreateDynamicType(entity.Key, entity.Value);
            entityTypes.Add(type);
        }

        services.AddSingleton(entityTypes);

        services.AddDbContext<DynamicDbContext>(options =>
            options.UseSqlServer("YourConnectionStringHere")
                   .ReplaceService<IModelCustomizer, DynamicModelCustomizer>());

        services.AddScoped(provider =>
        {
            var options = provider.GetRequiredService<DbContextOptions<DynamicDbContext>>();
            var entityTypes = provider.GetRequiredService<IEnumerable<Type>>();
            return new DynamicDbContext(options, entityTypes);
        });

        services.AddScoped<IMigrator>(provider =>
        {
            var context = provider.GetRequiredService<DynamicDbContext>();
            return context.Database.GetService<IMigrator>();
        });

        services.AddScoped<MigrationService>();
    }

    private static Dictionary<string, Dictionary<string, Type>> GetDynamicEntities()
    {
        return new Dictionary<string, Dictionary<string, Type>>
        {
            {
                "DynamicEntity1", new Dictionary<string, Type>
                {
                    { "Id", typeof(int) },
                    { "Name", typeof(string) }
                }
            },
            {
                "DynamicEntity2", new Dictionary<string, Type>
                {
                    { "Id", typeof(int) },
                    { "Description", typeof(string) }
                }
            }
        };
    }

    private static void InsertTestData(DynamicDbContext context)
    {
        var dynamicEntity1Type = context.Model.FindEntityType("DynamicEntity1").ClrType;
        var dynamicEntity2Type = context.Model.FindEntityType("DynamicEntity2").ClrType;

        var dynamicEntity1 = Activator.CreateInstance(dynamicEntity1Type);
        var dynamicEntity2 = Activator.CreateInstance(dynamicEntity2Type);

        dynamicEntity1Type.GetProperty("Id").SetValue(dynamicEntity1, 1);
        dynamicEntity1Type.GetProperty("Name").SetValue(dynamicEntity1, "Test Name");

        dynamicEntity2Type.GetProperty("Id").SetValue(dynamicEntity2, 1);
        dynamicEntity2Type.GetProperty("Description").SetValue(dynamicEntity2, "Test Description");

        context.Add(dynamicEntity1);
        context.Add(dynamicEntity2);
        context.SaveChanges();
    }
} 

the migration history table is being created, but it’s not populated with migration entries. Additionally, the table for the new entity is not being created in the database.

New contributor

Guna Krishnamoorthy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật