首页 > 代码库 > EF 连接到 Azure-SQL
EF 连接到 Azure-SQL
给出具体实例之前:先说说我们为什么选择Azure SQL:
Azure SQL 具有哪些优点了:
1.自主管理 省去了日常管理本地SQL Server实例的时间成本。
2.高可用性 如果一台硬件出故障,SQL Azure提供的自动执行故障转移可以确保应用程序的可用性。
3.可扩展性 横向扩展,分割了数据,服务随着数据增长而扩展,数据减少而收缩。
4.数据库版本 根据你实际情况,选择不同的版本。
实例代码:
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());:注册一个事物处理程序
具体详情:http://www.cnblogs.com/prinsun/p/ef_connection_retry.html
使用指定的依赖关系解析程序接口,为依赖关系解析程序提供一个注册点,给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 = "2", Pwd = "21" }; 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的文件,日志就在里面。
当我运行程序之后,成功创建了数据。
日志文件
返回受影响行数一行,因为我只插入了一行吗。
希望你能从中获益:)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。