How to extend DbContext with partial class and partial OnModelCreating method in EntityFramework Core

前端 未结 3 1438
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 20:23

I\'m using EF Core and DatabaseFirst approach. My dbContext is created automatically by Scaffold-DbContext command.

I need to add some new DbSets into a

3条回答
  •  半阙折子戏
    2020-12-08 21:01

    You can't override methods in a partial class because all of the "parts" become a single class. But you can accomplish this by having the main OnModelCreating call a partial method. Like this:

    public partial class Db : DbContext
    {
        partial void OnModelCreating2(ModelBuilder modelBuilder)
        {
           //additional config
        }
    }
    
    public partial class Db : DbContext
    {
    
        public DbSet Persons { get; set; }
    
        partial void OnModelCreating2(ModelBuilder modelBuilder);
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            OnModelCreating2(modelBuilder);
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=localhost;database=efcore2test;integrated security=true");
            base.OnConfiguring(optionsBuilder);
        }
    }
    

提交回复
热议问题