2

Using EF Core, Fluent API, specifying a schema at table level is done like:

 modelBuilder.Entity<MyRecord>().ToTable("MyRecord", "mySchema");

Is there an alternative way to specify schema for a table, or multiple tables without having to string the table and schema names?

Just from the point of view of coding efficiency, it is a bit redundant to have to also include the table name when it maps directly to the entity name for each table / entity.

It can be set globally with modelBuilder.HasDefaultSchema("mySchema") but this won't help when working with different schemas.

JMP
  • 1,864
  • 2
  • 8
  • 16
  • 2
    Does this answer your question? [Entity Framework 6 - Code First: table schema from classes' namespace](https://stackoverflow.com/questions/29129476/entity-framework-6-code-first-table-schema-from-classes-namespace) – Crowcoder Mar 03 '21 at 13:04
  • 1
    Attribute notation is another way, but you can also use conventions – Chris Schaller Mar 03 '21 at 13:15
  • @ChrisSchaller can you point me to how to configure schema by convention? I'm unable to find anything except "by convention it uses dbo" – Crowcoder Mar 03 '21 at 13:23
  • Thanks both, Custom conventions seem to be EF only, not EF Core as far as i can see. I'll look into convention overrides and see if I can finf a solution there. – JMP Mar 03 '21 at 13:27
  • @Crowcoder -at first glance it point towards the answer being that it can't be done, unless convention overrides is the answer, which I don't know about currently so will look into... – JMP Mar 03 '21 at 13:29
  • 1
    you can also get around the "string" issue by using `nameof(MyRecord)` Yes it seems redundant, but if you want to change the default schema _or_ tablename, then you must specify both. – Chris Schaller Mar 03 '21 at 13:35

1 Answers1

2

Currently (EFC 5.x) there is no public fluent API for setting just the schema of an entity type, but as usual in such cases you can use the public metadata API instead. In this this particulars case - the SetSchema method:

modelBuilder.Entity<MyRecord>().Metadata.SetSchema("mySchema");
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343