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 ...
随机推荐
- ZT 基于git的版本管理思路
http://nvie.com/posts/a-successful-git-branching-model/ 分为5种分支: feature:功能分支,开发人员在此种分支下开发新的功能,开发完成后m ...
- [Erlang12] Mnesia分布式应用
[Erl_Question12] Mnesia分布式应用 情景: 设计一个图书管理系统,需求: 1. 基本的增删查改功能; 2. 支持多节点备份(其中一个节点挂了进,对外接口不影响). 方案一: Er ...
- SQL函数(不定时更新)
sum求和:select sum(a) from table1 group by b 依据b列为a列求和 distinct去除重复:select distinct(a) from table1 ...
- 解决:The APR based Apache Tomcat Native library which allows optimal performance in production...
tomcat日志apr报错引发的基于Tomcat Native加速Tomcat性能 tomact服务启动报错日志如下:息: The APR based Apache Tomcat Native lib ...
- 【题解】 LA3708 Graveyard
题目大意 在一个圆周长为10000的圆上等距离分布n个雕塑,现在有m个新加入的雕塑(还是要求等距离摆放),问n个雕塑移动的总距离的最小值. Solution 显然必然会有一个雕塑不移动,所以可以直接不 ...
- [转]解读Unity中的CG编写Shader系列4——unity中的圆角矩形shader
上篇文章中我们掌握了表面剔除和剪裁模式这篇文章将利用这些知识实现一个简单的,但是又很常用的例子:把一张图片做成圆角矩形 例3:圆角矩形Shader好吧我承认在做这个例子的时候走了不少弯路,由于本人对矩 ...
- iOS 轻松使用 App 数据统计
想获取用户各项行为数据吗? 想轻松查看用户行为图表吗? 想高效进行 App 运营管理吗? 想,来我带你玩转 App 数据统计.这里我使用专业.轻便的 JAnalytics. 本文内容分为两部分:代码示 ...
- 编译图像质量分析库iqa
介绍 iqa库是我在GitHub上偶然发现的一个具有MSE, PSNR, SSIM, MS-SSIM等图像质量分析算法的库,觉得还不错,就把它下载下来编译,编译后生成静态的库.以下是我总结的编译方 ...
- Using Request Headers for Metadata Address
问题描述 我将一个在本地调试正常的service部署到服务器后遇到了添加服务引用失败的问题.在把配置文件中基址使用的localhost替换成服务器的ip地址后问题得到了解决.但我感觉这并不是一个因为粗 ...
- window.onload和JQuery中$(function(){})的区别即其实现原理
一.区别 window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行. 在Jquery中$(function(){ })和$(document).ready(function(){ ...