10

We have a database where the tables are organized in multiple schemas like Common.User and Product.Order. There are also tables with the same name in different schemas.

Is it somehow possible to use this schemas to organize the DbSet objects within the DBContext? The best solution for us would be to access the user object like dbcontext.Common.User. Is this possible?

In general, what is the best strategy to work with multiple database schemas in EF Core?

Edit: The question does not target on how to map tables from different schemas (entity.ToTable("User","Common")). It is about organizing the mapped tables according to their schema within the DbContext.

user9405863
  • 1,506
  • 1
  • 11
  • 16
Rhopi
  • 101
  • 1
  • 6
  • Possible duplicate of [Using Entity Framework 6 with Multiple DB Schemas but using One DBContext](https://stackoverflow.com/questions/36576932/using-entity-framework-6-with-multiple-db-schemas-but-using-one-dbcontext) – Seididieci Mar 15 '18 at 08:51
  • @Seididieci Please see Edit. – Rhopi Mar 15 '18 at 09:10
  • Sorry i misundestood your question... Usually to separate concerns i use several classes and use them as properties of the main one. Then I consume them like `MainClass.OtherClass.Property` but i doubt that EF will understand it in a DBContext. – Seididieci Mar 15 '18 at 09:18
  • I have already tried that and the DbSet objects in the sub class were not initialized. – Rhopi Mar 15 '18 at 09:24
  • Then I think you have two ways: 1) Have multiple DBContext (one per schema) and a wrapping class with a property per context. 2) Use some naming convention for the DbSet properties... – Seididieci Mar 15 '18 at 09:34
  • Are multiple DbContext considered good practice? There are foreign keys across the schemas, would that be a problem? Is there an example somewhere? – Rhopi Mar 15 '18 at 09:46
  • [This](https://stackoverflow.com/questions/11197754/entity-framework-one-database-multiple-dbcontexts-is-this-a-bad-idea) question may help you... They says is not a bad idea, having a big common DbContext for db creation/migration and one DbContext per concern. – Seididieci Mar 16 '18 at 16:59
  • Did you ever figure out how to do this? – CodeRedick Nov 15 '22 at 21:34

0 Answers0