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的更多相关文章

  1. SQL Server ->> 使用Azure Active Directory Authentication连接到Azure SQL Database

    SQL Server 2016以后支持Azure AD集成验证,这当中有些数据驱动必须在高版本才可以使用,支持的包括sqlcmd,SSDT,JDBC,ODBC,SSMS等. 对于SSIS来讲,我们需要 ...

  2. 在 Azure 上创建和链接 Azure SQL 数据库

    本快速入门介绍了如何在 Azure 门户中创建并连接 Azure SQL 数据库.在本教程中完成的所有操作均符合 1 元试用条件. 开始之前 如果您还没有 Azure 账户,可以申请 1 元试用账户. ...

  3. 【数据库-Azure SQL Database】如何创建事务复制将本地数据同步到 SQL Azure

    Azure SQL DB 可以被配置成为 SQL Server 事务复制的一个订阅者( subscriber ). 主要应用场景有两种: 将您的数据迁移到 Azure SQL DB, 并且没有宕机时间 ...

  4. 连接到 Azure 上的 SQL Server 虚拟机(经典部署)

    概述 本主题介绍如何连接到运行于 Azure 虚拟机的 SQL Server 实例. 它介绍了一些常规连接方案,并提供了在 Azure VM 中配置 SQL Server 连接的详细步骤. Impor ...

  5. 使用SSMS 2014将本地数据库迁移到Azure SQL Database

    使用SQL Server Management Studio 2014将本地数据库迁移到Azure SQL Database的过程比较简单,在SSMS2014中,有一个任务选项为“将数据库部署到Win ...

  6. Java连接Azure SQL Database

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

  7. Azure SQL Database (22) Azure SQL Database支持中文值

    <Windows Azure Platform 系列文章目录> 在笔者之前的文章里,已经介绍了如何使Azure SQL Database支持中文: SQL Azure(七) 在SQL Az ...

  8. 如何將 MySQL 資料庫轉移到 Microsoft SQL Server 與 Azure SQL Database

    MySQL 是相當常用之資料庫伺服器,而微軟雲端服務 Microsoft Azure 上 Azure SQL Database 是一個功能強大且經濟實惠的選擇,透過本篇文章,使用 SQL Server ...

  9. azure sql database CPU troubleshooting

    描述 最新我们一个稳定运行快一年的项目突然出现CPU方面的性能问题,该项目使用的azure sql database  P2 500DTU,运维同事监控到CPU使用非常高,客户反馈系统运行也比较卡.看 ...

  10. PowerShell 操作 Azure SQL Active Geo-Replication 实战

    <Azure SQL Database Active Geo-Replication简介>一文中,我们比较全面的介绍了 Azure SQL Database Active Geo-Repl ...

随机推荐

  1. 小程序:web-view采坑指南

    最近负责开发的[广州医保查询]小程序已经发布上线,其中使用web-view组件完成的[在线绑定社保卡]核心流程,遇到了一些坑,现总结如下: 首先,让我们一起看看什么是web-view ? 小程序api ...

  2. oracle数据库中将clob字段内容利用java提取出至文本文档中

    代码段: 1.执行clob转String public static String ClobToString(Clob sc) throws SQLException, IOException { S ...

  3. OCP 12c最新考试原题及答案(071-8)

    8.(5-4) choose the best answer:You need to produce a report where each customer's credit limit has b ...

  4. 3.iptables 扩展模块

    --tcp-flags 用于匹配报文的tcp头的标志位 iptables -t filter -I INPUT -p tcp -m tcp --dport 22  --tcp-flags SYN,AC ...

  5. Elasticsearch C# NEST IndexMany Children

    foreach (IEnumerable<object> batch in objects.Batch(1000)) { var indexResponse = client.Bulk(s ...

  6. 傻瓜式学Python3——列表

    前言: 好久不见,突然发觉好久没写博客了,最近迷上了 Python 无法自拔,了解了一下,Python 简单易学,尤其是接触过java的人,入门 Python 更是门槛极低,本着学习记录的原则,边学习 ...

  7. leetcode-812-Largest Triangle Area

    题目描述: You have a list of points in the plane. Return the area of the largest triangle that can be fo ...

  8. QRCode简介(收藏)

      一.什么是二维码:二维码 (2-dimensional bar code),是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的. 在许多种类的二维条码中,常 ...

  9. DEM反应添加顺序注意问题

    在含有DEM反应的dat中,均相反应的block要在DEM反应之前,例如: @(RXNS) (some reaction equations) @(END) @(DES_RXNS) (some rea ...

  10. 高阶篇:4.1.2.3)产品零件级别的QFDII

    本章目的:介绍产品零件级别的QFDII编写方法. 1.前言 这章接前面部件级别的QFDII. 产品零件级别的QFDII,其实就是将零件QFDII所得到的设计要求,进一步分配零件的特征(Part Cha ...