今天有一個小任務:要把一個數據的數據搬運到另一個數據庫(兩個數據庫的數據結構很不一樣)。
決定用.net core console app來跑,並且采用entityframework 去做數據CRUD.
環境:win10 + vs2017rc
第一步: 創建一個.net core console app。
第二步:安裝EFCore package 和 design(以前vs是有EF項目模板的,core版本現在沒有,所有安裝這個工具來創建ModelsType Context等).
工具-->Nuget包管理器-->程序包管理控制台
1.Install-package microsoft.entityframeworkcore.sqlserver
2.Install-package microsoft.entityframeworkcore.sqlserver.design
3.Install-Package Microsoft.EntityFrameworkCore.Tools –Pre (-Pre應該是預覽版的意思)
第三步:使用工具的scaffold-dbcontext(數據庫上下文腳手架)指令來生成models和context。
指令詳細介紹:
Scaffold-DbContext [-Connection] <String> [-Provider] <String> [-OutputDir <String>] [-Context <String>]
[-Schemas <String>] [-Tables <String>] [-DataAnnotations] [-Force] [-Project <String>]
[-StartupProject <String>] [-Environment <String>] [<CommonParameters>]
PARAMETERS
-Connection <String>
Specifies the connection string of the database.
-Provider <String>
Specifies the provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer.
-OutputDir <String>
Specifies the directory to use to output the classes. If omitted, the top-level project directory is used.
-Context <String>
Specifies the name of the generated DbContext class.
-Schemas <String>
Specifies the schemas for which to generate classes.
-Tables <String>
Specifies the tables for which to generate classes.
-DataAnnotations [<SwitchParameter>]
Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API.
-Force [<SwitchParameter>]
Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten.
-Project <String>
Specifies the project to use. If omitted, the default project is used.
-StartupProject <String>
Specifies the startup project to use. If omitted, the solution's startup project is used.
-Environment <String>
Specifies the environment to use. If omitted, "Development" is used.
本文實例:
Scaffold-dbcontext "Server=192.168.1.159;database=SGD.Invest;Integrated Security=false;user id=****;password=*****" Microsoft.EntityFrameworkCore.SqlServer -outputdir v1/models
Integrated Security(是否集成認證 windows賬戶認證的意思)
第四步:上面我們已經看到Context文件已經生成,只需要生成它的實例就可以使用了。
附:
配置dbcontext的官方文檔:https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext