EF 连接到 Azure-SQL
using Autofac;
using Autofac.Integration.Mvc;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using WebApplication3.Models; namespace WebApplication3
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{ var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.Register<UserContext>((_) => new UserContext());
builder.Register<IDbInterceptor>((_) => new MyNLogInterceptor()); builder.Register<Func<IDbExecutionStrategy>>((_) => () => new SqlAzureExecutionStrategy());
builder.Register<Func<TransactionHandler>>((_) => () => new CommitFailureHandler()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //添加一个依赖关系解析
DbConfiguration.Loaded += (s, e) =>
e.AddDependencyResolver(new MyAutofacDependencyResolver(container), overrideConfigFile: false); AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
} public class MyNLogInterceptor : IDbCommandInterceptor
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
} public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
LogCommandComplete(command, interceptionContext);
} public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
} public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
LogCommandComplete(command, interceptionContext);
} public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
} public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
LogCommandComplete(command, interceptionContext);
} private void LogCommandComplete<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
if (interceptionContext.Exception == null)
{
logger.Trace("Command completed with result {0}", interceptionContext.Result);
logger.Trace(command.CommandText);
}
else
{
logger.WarnException("Command failed", interceptionContext.Exception);
logger.Trace(command.CommandText);
}
}
} public class MyAutofacDependencyResolver : IDbDependencyResolver
{
private ILifetimeScope container; public MyAutofacDependencyResolver(ILifetimeScope container)
{
this.container = container;
} public object GetService(Type type, object key)
{
if (container.IsRegistered(type))
{
return container.Resolve(type);
} return null;
} public IEnumerable<object> GetServices(Type type, object key)
{
if (container.IsRegistered(type))
{
return new object[] { container.Resolve(type) };
} return Enumerable.Empty<object>();
}
}
}
builder.Register<Func<IDbExecutionStrategy>>((_) => () => new SqlAzureExecutionStrategy());:使用SsqlAzure 执行策略
builder.Register<Func<TransactionHandler>>((_) => () => new CommitFailureHandler());:注册一个事物处理程序
使用指定的依赖关系解析程序接口,为依赖关系解析程序提供一个注册点,给MVC提供依赖关系解析。
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
添加一个依赖关系解析,为EF提供依赖关系解析
DbConfiguration.Loaded += (s, e) =>
e.AddDependencyResolver(new MyAutofacDependencyResolver(container), overrideConfigFile: false);
MyNLogInterceptor:它可以侦听EF发送到数据库的命令
private void LogCommandComplete<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
if (interceptionContext.Exception == null)
{
成功记录日志,命令和完成结果
logger.Trace("Command completed with result {0}", interceptionContext.Result);
logger.Trace(command.CommandText);
}
else
{ 失败记录日志,命令和异常
logger.WarnException("Command failed", interceptionContext.Exception);
logger.Trace(command.CommandText);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.Models; namespace WebApplication3.Controllers
{
public class HomeController : Controller
{
public UserContext Ucontext;
public HomeController(UserContext context)
{
this.Ucontext = context;
}
// GET: Home
public ActionResult Index()
{
User user = new User { Name = "", Pwd = "" };
Ucontext.Users.Add(user); Ucontext.SaveChanges(); return Content("Yes");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Ucontext.Dispose();
}
base.Dispose(disposing);
}
}
}
释放资源
protected override void Dispose(bool disposing)
{
if (disposing)
{
Ucontext.Dispose();
}
base.Dispose(disposing);
}
实现依赖解析 和 日志记录 还要引入两个包。 1.NLog 2.Autofac
引入Nlog包之后到开Nlog.config取消注释,运行程序之后点击显示所有文件
将会出现一个Logs的文件,日志就在里面。 当我运行程序之后,成功创建了数据。
日志文件
返回受影响行数一行,因为我只插入了一行吗。
希望你能从中获益:)
EF 连接到 Azure-SQL的更多相关文章
- SQL Server ->> 使用Azure Active Directory Authentication连接到Azure SQL Database
SQL Server 2016以后支持Azure AD集成验证,这当中有些数据驱动必须在高版本才可以使用,支持的包括sqlcmd,SSDT,JDBC,ODBC,SSMS等. 对于SSIS来讲,我们需要 ...
- 在 Azure 上创建和链接 Azure SQL 数据库
本快速入门介绍了如何在 Azure 门户中创建并连接 Azure SQL 数据库.在本教程中完成的所有操作均符合 1 元试用条件. 开始之前 如果您还没有 Azure 账户,可以申请 1 元试用账户. ...
- 【数据库-Azure SQL Database】如何创建事务复制将本地数据同步到 SQL Azure
Azure SQL DB 可以被配置成为 SQL Server 事务复制的一个订阅者( subscriber ). 主要应用场景有两种: 将您的数据迁移到 Azure SQL DB, 并且没有宕机时间 ...
- 连接到 Azure 上的 SQL Server 虚拟机(经典部署)
概述 本主题介绍如何连接到运行于 Azure 虚拟机的 SQL Server 实例. 它介绍了一些常规连接方案,并提供了在 Azure VM 中配置 SQL Server 连接的详细步骤. Impor ...
- 使用SSMS 2014将本地数据库迁移到Azure SQL Database
使用SQL Server Management Studio 2014将本地数据库迁移到Azure SQL Database的过程比较简单,在SSMS2014中,有一个任务选项为“将数据库部署到Win ...
- Java连接Azure SQL Database
Azure SQL Database是Azure上的数据库PAAS服务,让用户可以快速的创建和使用SQL数据库而不用担心底层的备份,安全,运维,恢复等繁琐的工作,本文简单介绍如何使用Java程序连接到 ...
- Azure SQL Database (22) Azure SQL Database支持中文值
<Windows Azure Platform 系列文章目录> 在笔者之前的文章里,已经介绍了如何使Azure SQL Database支持中文: SQL Azure(七) 在SQL Az ...
- 如何將 MySQL 資料庫轉移到 Microsoft SQL Server 與 Azure SQL Database
MySQL 是相當常用之資料庫伺服器,而微軟雲端服務 Microsoft Azure 上 Azure SQL Database 是一個功能強大且經濟實惠的選擇,透過本篇文章,使用 SQL Server ...
- azure sql database CPU troubleshooting
描述 最新我们一个稳定运行快一年的项目突然出现CPU方面的性能问题,该项目使用的azure sql database P2 500DTU,运维同事监控到CPU使用非常高,客户反馈系统运行也比较卡.看 ...
- PowerShell 操作 Azure SQL Active Geo-Replication 实战
<Azure SQL Database Active Geo-Replication简介>一文中,我们比较全面的介绍了 Azure SQL Database Active Geo-Repl ...
随机推荐
- [linux] 查看SATA速度和具体设备
查看SATA速度和具体设备 SATA 速度确认 方法一 dmesg |grep SATA 输出 [ 2.977661] ahci 0000:00:17.0: AHCI 0001.0301 32 slo ...
- [Erlang04]为什么有了rpc还有net_kernel:connect/1?
问题描述: RPC(Remote Procedure Call)远程程序调用: 如果要给另一个节点发信息:可以简单写成: call(Msg,Node) -> {server,Node}!{sel ...
- mvc4开篇之BundleConfig(1)
新建一个mvc4默认项目,会看到以下目录 打开App_start 里面BundleConfig.cs文件 你会看到这么一段话: 有关 Bundling 的详细信息,请访问 http://go.micr ...
- Ocelot
Ocelot——初识基于.Net Core的API网关 Ocelot API网关的实现剖析 微服务网关Ocelot API网关Ocelot 使用Polly 处理部分失败问题 谈谈微服务中的 API 网 ...
- OCP 12c最新考试题库及答案(071-2)
2019-02-12 16:23:54 2.(4-7) choose the best answer:You need to display the first names of all cust ...
- SP2666 QTREE4 - Query on a tree IV(LCT)
题意翻译 你被给定一棵n个点的带边权的树(边权可以为负),点从1到n编号.每个点可能有两种颜色:黑或白.我们定义dist(a,b)为点a至点b路径上的权值之和. 一开始所有的点都是白色的. 要求作以下 ...
- 使用concat做字符串拼接和数据迁移
作用: 解决一开始数据库建立不合理造成的字段冗余,从而提取部分字段,数据迁移.拼接字符串的功能. 格式: concat(字段1,'间隔符',字段2....) concat_ws('间隔符',字段1,字 ...
- NSCharacterSet 关于字符串编码
此文转自:http://nshipster.cn/nscharacterset/ 只为个人为了查找问题方便才复制过来的....... 正如之前提前过的,基础类库(Foundation)拥有最好的.功能 ...
- 「案例」重新设计 Adobe 的文件类型图标
Adobe 的品牌设计团队负责为公司旗下桌面端.移动端和 web 端的产品进行品牌设计.品牌元素的形式很多,可以是两个字母的产品 logo,应用启动界面,产品里的图标等等. 一个很常见却常被忽视的品牌 ...
- easyui页面上显示和PL/SQL编码问题
在页面上,只需要显示人们看的懂的文字就行,但是在数据库里面就不一定了,一般情况下,在数据库里面存字母,数字等除了汉字以外的字符,存汉字有个问题,就是有时候不同oracle数据库的客户端会出现乱码问题: ...