Search code examples
c#asp.net-core-2.1ef-core-2.1

How to define schema table level


I am using EF Core 2.1 with C# for my application.

For some reason, there are a few tables for which I want the schema to be dbo while for others app

public class MyAppContext : DbContext
{
    private const string _dbSchema = "app";

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(_dbSchema);
        modelBuilder.ApplyConfiguration(new RegionConfiguration());
        base.OnModelCreating(modelBuilder);
    }
}

While for some entities, I want to override the default schema & set it.

public class RegionConfiguration : IEntityTypeConfiguration<Region>
{
    public void Configure(EntityTypeBuilder<Region> builder)
    {
        // Didn't find any such method -> builder.HasSchema("dbo"); 
        builder.HasKey(x => x.RegionId); //Primary Key
    }
}

How to address this?


Solution

  • Use ToTable method:

    public class RegionConfiguration : IEntityTypeConfiguration<Region>
    {
        public void Configure(EntityTypeBuilder<Region> builder)
        {
            builder.HasKey(x => x.RegionId); //Primary Key
            builder.ToTable("TableName", "dbo");
            // or  builder.ToTable(nameof(<entity>), "dbo");
        }
    }