4

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • Does this answer your question? [Dynamically changing schema in Entity Framework Core](https://stackoverflow.com/questions/39499470/dynamically-changing-schema-in-entity-framework-core) – Barr J Feb 17 '20 at 07:56
  • you can use Data Annotations approach by using Data Annotations [Table("blogs", Schema = "blogging")] or you can use Fluent API modelBuilder.Entity() .ToTable("blogs", schema: "blogging"); modelBuilder.HasDefaultSchema("blogging"); – Bob Ash Feb 17 '20 at 08:00

2 Answers2

3

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");
    }
}
Kgn-web
  • 7,047
  • 24
  • 95
  • 161
Vlad
  • 1,377
  • 2
  • 17
  • 29
  • For EntityFrameworkCore 5, the .ToTable() method is no longer available. How would one accomplish the same thing with EFCore5? – Solo812 Mar 28 '21 at 15:38
  • 1
    @Solo812 The method ToTable [still available](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationalentitytypebuilderextensions.totable?view=efcore-5.0#Microsoft_EntityFrameworkCore_RelationalEntityTypeBuilderExtensions_ToTable_Microsoft_EntityFrameworkCore_Metadata_Builders_EntityTypeBuilder_System_String_System_String_). Ensure, that you have added Microsoft.EntityFrameworkCore.Relational package to project references. – Vlad Mar 31 '21 at 11:36
2

As an option, you can also use DataAnnotations instead as alternative to FluentAPI. Both are fine.

[Table("Region",Schema = "dbo")]
public class Region {}
Nigel B
  • 3,577
  • 3
  • 34
  • 52
hastrb
  • 410
  • 4
  • 12