** 温馨提示:如需转载本文,请注明内容出处。**

本文链接: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的更多相关文章

  1. pymssql连接Azure SQL Database

    使用pymssql访问Azure SQL Database时遇到"DB-Lib error message 20002, severity 9:\nAdaptive Server conne ...

  2. 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移

    不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...

  3. 《python编程从入门到实践》读书实践笔记(二)

    本文是<python编程从入门到实践>读书实践笔记11章的内容,主要包含测试,为体现测试的重要性,独立成文. 11 测试代码 写在前面的话,以下是我这些年开发中和测试相关的血泪史. 对于一 ...

  4. Java连接Azure SQL Database

    Azure SQL Database是Azure上的数据库PAAS服务,让用户可以快速的创建和使用SQL数据库而不用担心底层的备份,安全,运维,恢复等繁琐的工作,本文简单介绍如何使用Java程序连接到 ...

  5. 用SSMS连接Azure Sql Database 与连接本地库的一些操作区别

    背景 我们知道Azure Sql Database 可以降低运维成本.是一种Pass模式,有资源弹性设置,可以自由调整资源自动对应不同业务高峰(当然也可以降低费用成本),也方便项目后期的资源扩展,以及 ...

  6. .NET Core 学习笔记3——EF Core

    EF Core (EntityFramework Core)是实体关系映射(O/RM)数据库访问框架.这个模式的好处就是让开发人员可以用对象模型来操作数据库,这是一种对开发人员较为友好的方式. O/R ...

  7. .net core 实践笔记(三)--封装底层

    前言: 有了前面的工作,简单的架子基本搭建起来了,因为条件有限,只能先测试SqlServer的了,源码放出来,也希望有兴趣的伙伴可以一起改善,相信可以成为未来进阶架构师的第一步,自己有小项目的时候可以 ...

  8. .net core 实践笔记(一)--开篇

    ** 温馨提示:如需转载本文,请注明内容出处.** 本文链接:https://www.cnblogs.com/grom/p/9902000.html  最近无聊自己设计了一个小项目,基本都使用想用没用 ...

  9. ASP.NET Core 折腾笔记二:自己写个完整的Cache缓存类来支持.NET Core

    背景: 1:.NET Core 已经没System.Web,也木有了HttpRuntime.Cache,因此,该空间下Cache也木有了. 2:.NET Core 有新的Memory Cache提供, ...

随机推荐

  1. PDO drivers no value in Windows 或 ndefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY'

    把办公室的drupal7.54版本放到自己的笔记本(OS:Windows10 Pro,php:7.0.9,mysql 5.7.11,apache:2.4)上运行不了,查看了各项配置应该没问题啊.之前还 ...

  2. (C# Window Service) Verify that you have sufficient privileges to start system services

    写了个Windows Service, 用Wix 写了个Installer,编译通过,生成了msi 安装文件,但是安装的时候总是提示: Product: KingPro Service -- Erro ...

  3. HDFS原理解析

    一.HDFS简介 HDFS为了做到可靠性(reliability)创建了多分数据块(data blocks)的复制(replicas),并将它们放置在服务器群的计算节点中(computer nodes ...

  4. Climbing Stairs 爬楼梯问题,每次可以走1或2步,爬上n层楼梯总方法 (变相fibonacci)

    You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb ...

  5. Monkey测试环境搭建

    一.JAVA环境的搭建 1.安装jdk-7u60-windows-x64(JAVA1.7.0,也可安装最新版的JAVA1.8.0),默认安装路径C盘: 2.JAVA环境变量的搭建: 我的电脑→右键属性 ...

  6. [Swift] 创建一个对象

    创建一个对象 先写一个People类 // // People.swift // Class // // Created by YouXianMing on 15/3/18. // Copyright ...

  7. [tools]notepad++当前文件路径不是工作路径

    Time:2015/04/09 描述: 在notepad++中运行lua,工作路径不是当前文件的路径,而是notepad++的安装目录 修改: 把差将中的NppExec --> Follow $ ...

  8. windows 下 gdb 的安装

    在 windows 下 gcc/g++ 的安装 这篇文章中已经提到,用MinGW Installation Manager可以方便地管理 MinGW 组件,因此使用该软件安装 gdb . 打开 Min ...

  9. Python学习---基于JQuery的Ajax实现[快捷+底层$.ajax]

    快捷API <1>$.get(url, [data], [callback], [type]) <2>$.post(url, [data], [callback], [type ...

  10. 企业级Ngnix基于域名的配置_server

    普通的nginx配置 egrep -v "#|^$" /usr/local/nginx/conf/nginx.conf.default 更改nginx的配置文件-->注意空格 ...