.net core 实践笔记(二)--EF连接Azure Sql
** 温馨提示:如需转载本文,请注明内容出处。**
本文链接:https://www.cnblogs.com/grom/p/9902098.html
笔者使用了常见的三层架构,Api展示层注入了Swagger,作为开发测试使用的文档界面,具体搭建教程网上资料很全,不在赘述。
数据库目前使用了SqlServer,建了几张表和测试数据后放到了Azure云服务器上,值得一提的是,不同于其他云服务器,Azure对于数据库进行了优化和精简(毕竟自己微软自己家的东西,权利就是大),优缺点清参照官网文档。
笔者体验下来的感觉就是使用门槛要比其他的家的云服务器大的多,用户的账号和Token等信息需要在Azure上配置,数据库上的权限比精简前可以说是小的多,但也安全。
ORM使用的是Entity Framework和Dapper,执行命令都是使用Dapper,毕竟比EF轻的多,EF是用来映射数据库实体类的,在.Net Core下,少了T4模板,我们就需要使用命令手动映射了。
安装EF的包
Install-Package Microsoft.EntityframeworkCore.SqlServer
Install-Package Microsoft.EntityframeworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
Install-Package Microsoft.EntityFrameworkCore
映射模型
Scaffold-DbContext -Force “Data Source=(local); Initial Catalog=Nagrand; Pooling=True; UID=sa;PWD=;connect Timeout=” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
据说能去的空格都要去掉,不然可能会拉取失败。
改装成拉Azure上的语句

Scaffold-DbContext -Force “Data Source=tcp:test-server.database.windows.net,; Initial Catalog=DBName; Pooling=True;Persist Security Info=False; UID=sa;PWD=;TrustServerCertificate=False;connect Timeout=” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
填坑:
- 如出现错误,请检查拉去的项目(类库)里是否都前面提到的几个包。
- 注意符号,博主把这个命令放到了OneNote里了,结果第二天就不能用了,试了好多遍发现引号莫名其妙变成中文的了,并且没有语法的错误提示!!
- 用到的账号和密码一定拿到SSMS里登录一下试试
- 博主使用命令安装包的时候发现项目下有分析器是异常状态,查看是引用了C盘的文件,这个要注意,迁移的时候如果没有这些文件可能会出异常,可以从Nugit包里找到这些包一个个手动安装,就不会有异常了。
Dapper
附上一个DapperHelper,用于与数据库的交互
public static class DapperHelper
{
#region 连接字符串
public static string CONN_STRING = "";
#endregion #region SELECT
/// <summary>
/// 获取数据集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sqlString"></param>
/// <param name="param"></param>
/// <param name="commandType"></param>
/// <param name="commandTimeout"></param>
/// <returns></returns>
public static List<T> GetList<T>(this string sqlString, object param = null, CommandType? commandType = CommandType.Text, int? commandTimeout = )
{
var list = new List<T>(); using (var db = new SqlConnection(CONN_STRING))
{
IEnumerable<T> ts = null;
if (null == param)
{
ts = db.Query<T>(sqlString, null, null, true, commandTimeout, commandType);
}
else
{
ts = db.Query<T>(sqlString, param, null, true, commandTimeout, commandType);
}
if (null != ts)
{
list = ts.AsList();
}
} return list;
} public static List<T> GetList<T>(this string sqlString)
{
return GetList<T>(sqlString, null, CommandType.Text);
} public static List<T> GetList<T>(this string sqlString, object param)
{
if (null == param)
{
return GetList<T>(sqlString);
} return GetList<T>(sqlString, param);
}
#endregion #region INSERT
/// <summary>
/// 单条数据写入 动态模板模式/T
/// </summary>
/// <param name="sqlString"></param>
/// <param name="param"></param>
/// <param name="commandType"></param>
/// <param name="commandTimeOut"></param>
/// <returns></returns>
public static bool Insert(this string sqlString, object param = null, CommandType commandType = CommandType.Text, int? commandTimeOut = )
{
return ExecuteNonQuery(sqlString, param, commandType, commandTimeOut);
} /// <summary>
/// 批量写入
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sqlString"></param>
/// <param name="list"></param>
/// <param name="commandType"></param>
/// <param name="commandTimeOut"></param>
/// <returns></returns>
public static bool Insert<T>(this string sqlString, List<T> list, CommandType commandType = CommandType.Text, int? commandTimeOut = )
{
var intResult = ; if (null != list && < list.Count)
{
using (var db = new SqlConnection(CONN_STRING))
{
intResult = db.Execute(sqlString, list, null, commandTimeOut, commandType);
}
} return intResult > ;
}
#endregion #region UPDATE
public static bool Update(this string sqlString, object param, CommandType commandType = CommandType.Text, int? commandTimeOut = )
{
return ExecuteNonQuery(sqlString, param, commandType, commandTimeOut);
}
#endregion #region DELETE
public static bool Delete(this string sqlString, object param, CommandType commandType = CommandType.Text, int? commandTimeOut = )
{
return ExecuteNonQuery(sqlString, param, commandType, commandTimeOut);
}
#endregion #region Private Methods
private static bool ExecuteNonQuery(this string sqlString, object param, CommandType commandType = CommandType.Text, int? commandTimeOut = )
{
var intResult = ;
using (var db = new SqlConnection(CONN_STRING))
{
if (null == param)
{
intResult = db.Execute(sqlString, null, null, commandTimeOut, commandType); }
else
{
intResult = db.Execute(sqlString, param, null, commandTimeOut, commandType);
}
} return intResult > ;
}
#endregion
}
一般数据库连接字符串需要放入配置文件,可以写入自带的appsetting.xml里或者新建其他的。
{
"ConnectionStrings": {
"DBConnection": "Data Source={Address};Initial Catalog={DBName};Pooling=True;Persist Security Info=False;UID={Account};PWD={Password};TrustServerCertificate=False;connect Timeout=10"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
然后在Setup中获取节点并复制到连接字符串
DapperHelper.CONN_STRING = Configuration.GetConnectionString("DBConnection");
整个架子基本搞定,下面就可以写业务接口了。
.net core 实践笔记(二)--EF连接Azure Sql的更多相关文章
- pymssql连接Azure SQL Database
使用pymssql访问Azure SQL Database时遇到"DB-Lib error message 20002, severity 9:\nAdaptive Server conne ...
- 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移
不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...
- 《python编程从入门到实践》读书实践笔记(二)
本文是<python编程从入门到实践>读书实践笔记11章的内容,主要包含测试,为体现测试的重要性,独立成文. 11 测试代码 写在前面的话,以下是我这些年开发中和测试相关的血泪史. 对于一 ...
- Java连接Azure SQL Database
Azure SQL Database是Azure上的数据库PAAS服务,让用户可以快速的创建和使用SQL数据库而不用担心底层的备份,安全,运维,恢复等繁琐的工作,本文简单介绍如何使用Java程序连接到 ...
- 用SSMS连接Azure Sql Database 与连接本地库的一些操作区别
背景 我们知道Azure Sql Database 可以降低运维成本.是一种Pass模式,有资源弹性设置,可以自由调整资源自动对应不同业务高峰(当然也可以降低费用成本),也方便项目后期的资源扩展,以及 ...
- .NET Core 学习笔记3——EF Core
EF Core (EntityFramework Core)是实体关系映射(O/RM)数据库访问框架.这个模式的好处就是让开发人员可以用对象模型来操作数据库,这是一种对开发人员较为友好的方式. O/R ...
- .net core 实践笔记(三)--封装底层
前言: 有了前面的工作,简单的架子基本搭建起来了,因为条件有限,只能先测试SqlServer的了,源码放出来,也希望有兴趣的伙伴可以一起改善,相信可以成为未来进阶架构师的第一步,自己有小项目的时候可以 ...
- .net core 实践笔记(一)--开篇
** 温馨提示:如需转载本文,请注明内容出处.** 本文链接:https://www.cnblogs.com/grom/p/9902000.html 最近无聊自己设计了一个小项目,基本都使用想用没用 ...
- ASP.NET Core 折腾笔记二:自己写个完整的Cache缓存类来支持.NET Core
背景: 1:.NET Core 已经没System.Web,也木有了HttpRuntime.Cache,因此,该空间下Cache也木有了. 2:.NET Core 有新的Memory Cache提供, ...
随机推荐
- laravel开发之-安装汉化语言包
第一种方法: 1.输入命令:composer require "overtrue/laravel-lang:dev-master" 2.将config/app.php中命令“Ill ...
- swiper移动端日历-1
先上图: 说明:这是基于移动端的,对于PC端浏览器支持不是很好(我测的结果是IE无效),另外这个swiper是4.x版本的 思路: 先引用css <link href="css/ ...
- Difference between scipy.fftpack and numpy.fft
scipy.fftpack 和 numpy.fft 的区别 When applying scipy.fftpack.rfft and numpy.fft.rfft I get the followin ...
- MySQL在线加字段实现原理
博客已转移到腾讯DBA博客 http://tencentdba.com/ 腾讯互娱内部维护了一个MySQL分支,基于官方5.5.24,实现了类似于Oracle 11g的快速加字段功能,这个分支我们内部 ...
- package.json作用
这个文档的内容是你必须要知道的,它必须是JSON文本格式.每个项目的根目录下面,一般都有一个package.json文件,定义了这个项目所需要的各种模块,以及项目的配置信息(比如名称.版本.许可证等元 ...
- 关于v$rowcache
关于v$rowcache column parameter format a21column pct_succ_gets format 999.9column updates format 999,9 ...
- 巧用花生壳将局域网内的FTP和www服务器发布到互联网
一.目的:用生壳发布FTP和mail服务器到互连网. 二.网络环境:(出租房多家共用路由器上网,ADSL的1Mbps带宽,动态PPPOE拨号,帐号和密码存储在soho路由器中,路由器自动联机上网,并为 ...
- yum 安装 lnmp
一. 系统 更新 yum -y update 二. 安装nginx 创建文件 vim /etc/yum.repos.d/nginx.repo 文件内容,这配置是安装最新的稳定版1.8 [nginx] ...
- LAMP配置NFS页面共享,autofs实现挂载,DNS实现名称解析,纯手动操作
0.实验架构: 共6台服务器 分工如下: 服务器 职责 IP地址 Centos版本 描述 A DNS 172.18.7.70 7 B Apache 172.18.7.71 7 httpd+php-fp ...
- [EffectiveC++]item21:Don't try to return a reference when you must return an object