EF connects to Azure-sql

Source: Internet
Author: User

Before giving a specific example: Let's talk about why we chose Azure SQL:
What are the benefits of Azure SQL:

1. Autonomic management eliminates the time cost of managing local instances of SQL Server on a daily basis.

2. high Availability If one hardware fails, SQL Azure provides automatic failover to ensure the availability of the application.

3. Scalability scale -out, split data, and services expand as data grows, shrinking as data shrinks.

4. database version Depending on your situation, choose a different version.

Instance code:

usingAUTOFAC;usingAUTOFAC.INTEGRATION.MVC;usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Common;usingSystem.Data.Entity;usingSystem.Data.Entity.Infrastructure;usingSystem.Data.Entity.Infrastructure.DependencyResolution;usingSystem.Data.Entity.Infrastructure.Interception;usingSystem.Data.Entity.SqlServer;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;usingSystem.Web.Routing;usingWebapplication3.models;namespacewebapplication3{ Public classMvcApplication:System.Web.HttpApplication {protected voidApplication_Start () {            varBuilder =NewContainerbuilder (); Builder. Registercontrollers (typeof(mvcapplication).            Assembly); Builder. Register<UserContext> (_)/=NewUserContext ()); Builder. Register<IDbInterceptor> (_)/=Newmynloginterceptor ()); Builder. Register<Func<IDbExecutionStrategy>> (_) = = () =Newsqlazureexecutionstrategy ()); Builder. Register<Func<TransactionHandler>> (_) = = () =NewCommitfailurehandler ()); varcontainer =Builder.            Build (); Dependencyresolver.setresolver (NewAutofacdependencyresolver (container)); //Add a dependency resolutionDbconfiguration.loaded + = (s, e) = =E.adddependencyresolver (NewMyautofacdependencyresolver (Container), Overrideconfigfile:false);            Arearegistration.registerallareas ();        Routeconfig.registerroutes (routetable.routes); }    }     Public classMynloginterceptor:idbcommandinterceptor {Private StaticNlog.logger Logger =NLog.LogManager.GetCurrentClassLogger ();  Public voidnonqueryexecuting (DbCommand command, dbcommandinterceptioncontext<int>Interceptioncontext) {        }         Public voidnonqueryexecuted (DbCommand command, dbcommandinterceptioncontext<int>Interceptioncontext)        {logcommandcomplete (command, Interceptioncontext); }         Public voidreaderexecuting (DbCommand command, dbcommandinterceptioncontext<dbdatareader>Interceptioncontext) {        }         Public voidreaderexecuted (DbCommand command, dbcommandinterceptioncontext<dbdatareader>Interceptioncontext)        {logcommandcomplete (command, Interceptioncontext); }         Public voidscalarexecuting (DbCommand command, dbcommandinterceptioncontext<Object>Interceptioncontext) {        }         Public voidscalarexecuted (DbCommand command, dbcommandinterceptioncontext<Object>Interceptioncontext)        {logcommandcomplete (command, Interceptioncontext); }        Private voidlogcommandcomplete<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 classMyautofacdependencyresolver:idbdependencyresolver {PrivateIlifetimescope container;  Publicmyautofacdependencyresolver (Ilifetimescope container) { This. Container =container; }         Public ObjectGetService (Type type,Objectkey) {            if(container. Isregistered (type)) {returncontainer.            Resolve (type); }            return NULL; }         Publicienumerable<Object> getservices (Type Type,Objectkey) {            if(container. Isregistered (type)) {return New Object[] {container.            Resolve (Type)}; }            returnenumerable.empty<Object>(); }    }}


Builder. Register<func<idbexecutionstrategy>> (_) = () = new Sqlazureexecutionstrategy ());: Use Ssqlazure Execution policy
Builder. Register<func<transactionhandler>> (_) = () = new Commitfailurehandler ());: Register a thing handler

Specific details: http://www.cnblogs.com/prinsun/p/ef_connection_retry.html



Provides a registration point for the dependency resolver using the specified dependency resolver interface, which provides dependency resolution for MVC. Dependencyresolver.setresolver (new Autofacdependencyresolver (container));

Add a dependency resolution that provides dependency resolution for EF dbconfiguration.loaded + = (s, e) = E.adddependencyresolver (New Myautofacdependencyresolver (container), overrideconfigfile:false);


Mynloginterceptor: It can listen to the commands that EF sends to the database
private void logcommandcomplete<tresult> (DbCommand command, dbcommandinterceptioncontext<tresult> Interceptioncontext)        {            if (interceptioncontext.exception = = null)            {
Log successfully logged, command, and completion results logger. Trace ("Command completed with result {0}", Interceptioncontext.result); Logger. Trace (Command.commandtext); } Else { failed log, command, and exception logger. Warnexception ("Command failed", interceptioncontext.exception); Logger. Trace (Command.commandtext); } }
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;usingWebapplication3.models;namespacewebapplication3.controllers{ Public classHomecontroller:controller { PublicUserContext Ucontext;  PublicHomeController (UserContext context) { This. Ucontext =context; }        //Get:home         PublicActionResult Index () {User User=NewUser {Name ="2", PWD =" +" };            UCONTEXT.USERS.ADD (user);            Ucontext.savechanges (); returnContent ("Yes"); }        protected Override voidDispose (BOOLdisposing) {            if(disposing) {ucontext.dispose (); }            Base.        Dispose (disposing); }    }}

Freeing resources

protected override void Dispose (bool disposing)        {            if (disposing)            {                ucontext.dispose ();            }            Base. Dispose (disposing);        }


The implementation of dependency resolution and  logging  also introduces two packages.

1.NLog 2.AUTOFAC


After introducing Nlog package to open Nlog.config uncomment, run the program and click Show All Files
A logs file will appear and the log will be inside.


After I run the program, the data is created successfully.



Log file

  Returns the number of rows affected because I only inserted one row.  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.