简体   繁体   中英

Run Scaffold DBContext without overwriting custom code in Entity Framework core

I'm using EF Core and DB First Approach. I generate my DBContext and entities class using Scaffold-DbContext and it gave me expected result, but when i run Scaffold-DbContext command again with -Force , it will overwrite my DBContext File

I'm using multitenant, and i have custom code inside DBContext file (new constructor, connection sting in OnConfiguring method)

how i can update my Models without overwrite DBContext File?

    public partial class MyContext : DbContext
    {
        private readonly ITenantDatabaseProvider _tenantProvider;

        public MyContext()
        {
        }

        public MyContext(DbContextOptions<MyContext> options)
            : base(options)
        {
        }
        public MyContext(ITenantDatabaseProvider tenantProvider)
        {
            _tenantProvider = tenantProvider;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(_tenantProvider.GetTenantConnectionString().Result);
                //.AddInterceptors(new HintCommandInterceptor());
            }

            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }
        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
        
    }

While other answer tells to use different constructor, it does not explain how and why.

It is way cleaner to have db context separate from the concept of tenants, the only thing you need from your tenant is connection string? Well, you can pass it via options.

public MyContext(DbContextOptions<MyContext> options)
    : base(options)
{
}

To keep the same logic, use dynamic building of options for each db context instance

services.AddDbContext<ApplicationCoreDbContext>((services, builder) =>
{
    var tenantProvider = services.GetRequiredService<ITenantDatabaseProvider>();
    builder.UseSqlServer(tenantProvider.GetTenantConnectionString().Result);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM