今天有一个小任务:要把一个数据的数据搬运到另一个数据库(两个数据库的数据结构很不一样)。

决定用.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

posted on 2017-02-27 14:51  countrybuilder  阅读(8610)  评论(1编辑  收藏  举报