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. Linux常用命令,学的时候自己记的常用的保存下来方便以后使用 o(∩_∩)o 哈哈

    service httpd restart 重启Apache service mysqld restart 重启mysql [-][rwx][r-x][r--] 1 234 567 890 421 4 ...

  2. VMware下拷过来的Linux系统ifconfig下没有网络问题

    拷了同事的Linux系统,拷过来时还可以用,今天再打开发现找不到ip了,于是就在网上找解决方法,因本人从没接触过Linux所以查的挺多的但解决的方法试了好几个就是不行,后面找到的有效的解决方法有: L ...

  3. Re:从零开始的Spring Security Oauth2(三)

    上一篇文章中我们介绍了获取token的流程,这一篇重点分析一下,携带token访问受限资源时,内部的工作流程. @EnableResourceServer与@EnableAuthorizationSe ...

  4. C#应用程序所有已经打开的窗体的集合

    获取所有打开的窗体的集合 Application.OpenForms 获取其中的某个窗体 Application.OpenForms["窗体名"]

  5. 项目前端打包工具从 NEJ 切换成 webpack

    此文已由作者张磊授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 这里不讨论 NEJ 和 webpack 的优劣,仅从技术角度来探寻一下能否实现,以及实现的代价. 前言 上一篇 ...

  6. 数数(高维DP)

    T1 数数 [问题描述] fadbec 很善于数数,⽐如他会数将 a 个红球,b 个黄球,c 个蓝球,d 个绿球排成⼀列,任意相邻不同⾊的数⽬. 现在 R 君不知道 fadbec 数的对不对,想让你也 ...

  7. js计算机样式window.getComputedStyle(ele,null)与

    一.getComputedStyle兼容IE8以上,范户籍的计算样式的值都是绝对值,没有相对单位(如:width:10em; 它打印出来是160px) window.getComputedStyle( ...

  8. linux密码修改实验

    1.在单用户模式下进行引导 在不同的运行级别中,一个重要的运行级别就是单用户模式(运行级别1),该模式中,只有一个系统管理员使用特定的机器,而且尽可能少地运行系统服务,其中包含登录.单用户模式对少数管 ...

  9. 移动 UX 设计:如何设计推送通知

    这个问题你一定想过,在移动用户体验设计领域中,如何设计好一条简单的推送通知. 你注意过么,每天从不同的 App 上收到的大量的推送通知与提醒,这些通知里有多少你真的有兴趣? 每天,用户对各种没用的通知 ...

  10. jxl操作excel单个单元格换行和获取换行

    excel中同表格换行: a+"\n"+b 1.读取 String str = sheet.getCell(c, r).getContents(); String[] split ...