转自:https://www.jianshu.com/p/15a557ac43d9
1.连接mysql
第一步,新建asp.net core项目
![](http://upload-images.jianshu.io/upload_images/3151547-341d382d93711fe1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
新建项目
本例程作简单演示两种数据库的连接,为简便,新建一个默认webapi项目,添加mysql的.net core组件包,目前只有预览版。注意:core 1.0 1.1可以用mysql官方的 ,2.0就会报错建议用pomelo
![](http://upload-images.jianshu.io/upload_images/3151547-1b09e21d1c2b688e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
mysql 1.1
![](http://upload-images.jianshu.io/upload_images/3151547-80bdc8c9ae50a4c4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
pomelo 2.0
接着新建code first 数据库实体
![](http://upload-images.jianshu.io/upload_images/3151547-8f2a141c827baf21.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
code first
接着在startup.cs文件写入配置
![](http://upload-images.jianshu.io/upload_images/3151547-3e3b13f07e184675.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
startup.cs
在appsetting.json文件中写入连接字符串 ,注意字符串名字必须和上步中的一致,SslMode必须要。
![](http://upload-images.jianshu.io/upload_images/3151547-8352635bd3a40207.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
appsetting.json
接下来在controller中写个简单的方法,查询第一条数据再返回json。
![](http://upload-images.jianshu.io/upload_images/3151547-4f24293e92be3455.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
APIController
运行结果如下
![](http://upload-images.jianshu.io/upload_images/3151547-0551d1699926f352.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/446)
这是运行结果
2.MSSql的连接方式和mysql的差不多,需安装
![](http://upload-images.jianshu.io/upload_images/3151547-fe18add553416d90.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
支持.net core 2.0 修改下连接字符串即可。