Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To handle multiple schemas in one DBContext

I am using an existing Database with a new ASP.Net Core 2.0 application. The database has two schemas, dbo and notinapplication. I do not want to create model of notinapplication schema tables. So I use the following code in Package manager and it works fine.

Scaffold-DbContext "Server=localhost; Database=TestServer; Trusted_Connection=True; 
MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
-UseDatabaseNames -Force -Context "DbContext" -Schema "dbo"

This way I only get tables from dbo in DbContext and the notinapplication schema tables are ignored.

However now I have a new schema called user that needs to be part of the model.

Scaffold-DbContext "Server=localhost; Database=TestServer; Trusted_Connection=True; 
MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
-UseDatabaseNames -Force -Context "DbContext" -Schema "user"

But using the above code eliminates the tables from dbo schema. What are my options to have tables of both schemas in DBContext while ignoring the notinapplication schema.

And if I indeed have to create different contexts, is it possible to query from multiple DB contexts in one query?

like image 911
TheFallenOne Avatar asked Apr 05 '19 21:04

TheFallenOne


People also ask

Can you have multiple schemas?

In the Oracle database system, the term database schema, which is also known as "SQL schema," has a different meaning. Here, a database can have multiple schemas (or “schemata,” if you're feeling fancy). Each one contains all the objects created by a specific database user.

What is scaffold DbContext command?

Scaffold-DbContext commands help scaffolding entity type classes and a DbContext class based on a database schema thereby automating the code generation technique related to database access.

How do I set schema name in entity Framework?

As with any code-first schema customization, you can do this by using the entity classes' attributes or through the DbModelBuilder API. With data annotations, you can use the optional second parameter of the Table attribute to specify the schema name. The code in Figure 3 implements this change in the model.


1 Answers

All you need to do to provide multiple values is to use the 'array syntax'.

-Schema "schema1","schema2","schema3"

In your case, you have to do

Scaffold-DbContext "Server=localhost; Database=TestServer; Trusted_Connection=True; 
MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
-UseDatabaseNames -Force -Context "DbContext" -Schema "dbo","user"
like image 134
The_Outsider Avatar answered Sep 21 '22 02:09

The_Outsider