zoukankan      html  css  js  c++  java
  • EF 连接到 AzureSQL

    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 = "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的文件,日志就在里面。


    当我运行程序之后,成功创建了数据。



    日志文件

    返回受影响行数一行,因为我只插入了一行吗。
    希望你能从中获益:)
  • 相关阅读:
    .NET 环境中使用RabbitMQ
    WPF窗口模板——Style样式
    C#获取当前日期时间
    C#解析JSON字符串总结
    c#简单加密和对称加密
    List<T>转换为二维数组
    java后台导出pdf
    C# 创建 读取 更新 XML文件
    python 第三天
    编写登录接口
  • 原文地址:https://www.cnblogs.com/liek/p/3911520.html
Copyright © 2011-2022 走看看