天天看點

database first生成ModelScaffold-DbContext指令

文章目錄

  • Scaffold-DbContext指令
    • sqlserver
    • mysql
        • Scaffolding a Database by Filtering Tables
        • Scaffolding with Multiple Schemas

Scaffold-DbContext指令

參數 描述
-Connection 資料庫的連接配接字元串
-Provider 連接配接資料庫的驅動,預設一般選擇安裝的Microsoft.EntityFrameworkCore.SqlServer
-OutputDir 生成的模型路徑,路勁為啟動項目的相對路勁
-ContextDir 生成的Context路徑,路徑為啟動項目的相對路徑
-Context 生成的Context名稱
-Schemas <String[]> 選擇資料的架構,預設選擇所有。例如:(dbo.)
-Tables <String[]> 選擇要生成的資料表,預設選擇所有,也可以自行指定
-UseDatabaseNames 使用與資料庫中顯示的完全相同的表和列名稱。如果省略此參數,則更改資料庫名稱以更符合C#名稱樣式約定。
-force 重新生成,覆寫掉已經建立的檔案

例如:

sqlserver

  • 生成全部Model
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
           
  • 選擇生成的Model
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables "Blog","Post" -ContextDir Context -Context BlogContext
           

mysql

官網位址:https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-scaffold-example.html

Scaffolding a Database by Filtering Tables

It is possible to specify the exact tables in a schema to use when scaffolding database and to omit the rest. The command-line examples that follow show the parameters needed for filtering tables.

.NET Core CLI:

dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila -t actor -t film -t film_actor -t language -f
           

Package Manager Console in Visual Studio:

Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -OutputDir Sakila -Tables actor,film,film_actor,language -f
           

Scaffolding with Multiple Schemas

When scaffolding a database, you can use more than one schema or database. Note that the account used to connect to the MySQL server must have access to each schema to be included within the context. Multiple-schema functionality was introduced in Connector/NET 6.10.3-rc and 8.0.9-dmr releases.

The following command-line examples show how to incorporate the sakila and world schemas within a single context.

.NET Core CLI:

dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila --schema sakila --schema world -f
           

Package Manager Console in Visual Studio:

Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -OutputDir Sakila -Schemas sa
           

繼續閱讀