EntityFramework6.0 SQL read-write split Interceptor vs. MVC Action Interceptor

Source: Internet
Author: User

Dbcommandinterceptor class intercept for EF:

EF6.1 also out a lot of days, 6.1 compared to 6.0 has a big feature is the new System.Data.Entity.Infrastructure.Interception namespace, The objects under this namespace allow us to get to know some of the information about the EF runtime more easily, and of course we want to see the SQL statements generated by EF, not much, and start doing it;

classEfintercepterlogging:dbcommandinterceptor {Private ReadOnlyStopwatch _stopwatch =NewStopwatch ();  Public Override voidscalarexecuting (System.Data.Common.DbCommand command, dbcommandinterceptioncontext<Object>Interceptioncontext) {            Base.            Scalarexecuting (command, Interceptioncontext); _stopwatch.        Restart (); }         Public Override voidscalarexecuted (System.Data.Common.DbCommand command, dbcommandinterceptioncontext<Object>Interceptioncontext) {_stopwatch.            Stop (); if(Interceptioncontext.exception! =NULL) {Trace.traceerror ("exception:{1} \ r \ n-Error executing command: {0}", Command.commandtext, interceptionContext.Exception.ToString ()); }            Else{trace.traceinformation ("\ r \ n Execution time: {0} milliseconds \r\n-->scalarexecuted.command:{1}\r\n", _stopwatch.            Elapsedmilliseconds, Command.commandtext); }            Base.        scalarexecuted (command, Interceptioncontext); }         Public Override voidnonqueryexecuting (System.Data.Common.DbCommand command, dbcommandinterceptioncontext<int>Interceptioncontext) {            Base.            Nonqueryexecuting (command, Interceptioncontext); _stopwatch.        Restart (); }         Public Override voidnonqueryexecuted (System.Data.Common.DbCommand command, dbcommandinterceptioncontext<int>Interceptioncontext) {_stopwatch.            Stop (); if(Interceptioncontext.exception! =NULL) {Trace.traceerror ("exception:{1} \ r \ n-Error executing command:\r\n {0}", Command.commandtext, interceptionContext.Exception.ToString ()); }            Else{trace.traceinformation ("\ r \ n Execution time: {0} milliseconds \r\n-->nonqueryexecuted.command:\r\n{1}", _stopwatch.            Elapsedmilliseconds, Command.commandtext); }            Base.        nonqueryexecuted (command, Interceptioncontext); }         Public Override voidreaderexecuting (System.Data.Common.DbCommand command, dbcommandinterceptioncontext< System.data.common.dbdatareader>Interceptioncontext) {            Base.            Readerexecuting (command, Interceptioncontext); _stopwatch.        Restart (); }         Public Override voidreaderexecuted (System.Data.Common.DbCommand command, dbcommandinterceptioncontext< System.data.common.dbdatareader>Interceptioncontext) {_stopwatch.            Stop (); if(Interceptioncontext.exception! =NULL) {Trace.traceerror ("exception:{1} \ r \ n-Error executing command:\r\n {0}", Command.commandtext, interceptionContext.Exception.ToString ()); }            Else{trace.traceinformation ("\ r \ n Execution time: {0} milliseconds \ r \-->readerexecuted.command:\r\n{1}", _stopwatch.            Elapsedmilliseconds, Command.commandtext); }            Base.        readerexecuted (command, Interceptioncontext); }    }
View Code

The above code requires a namespace:

Using System.Data.Entity.Infrastructure.Interception;
Using System.Diagnostics;

From the method name we can see roughly three categories: Read class Sql,[reader], non-read class of Sql,[nonquery], and [Scalar], this kind of use less, with the original ADO type Basic, like, Not much. Each method of the SQL statement type has to be executed before executing, executed after executed, from the name we can see the AOP figure ha, next see how to use it ...

Well, yes, it's that simple, and of course you can put that code in the red line in the global file.

Let's see how it works.

Personal feeling is more than with what plug-in, third-party class library, sqlprofile What convenient point, with the blog park Google search a bit, seemingly did not find other garden friends write this method, may be too simple, are not willing to write, or trouble recommend let more friends see!

-------

MVC Interceptor:

MVC filter onactionexecuting () Gets the trigger controller, Action, etc. in the filter

usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingsystem.web; usingSYSTEM.WEB.MVC; usingSystem.Web.Routing; namespaceFB. Cms. Mvcsite { Public classRouteconfig { Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); Routes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}, namespaces:New string[] {"FB. Cms. MvcSite.Areas.admin.Controllers"}//If there are multiple home controllers in the project, you need to set the home controller's namespace              ). Datatokens.add (" Area","Admin")//. Datatokens.add ("area", "admin") means that the index view of the home controller in the admin area of the zone is set as the default startup item            ; }      }  }  
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingsystem.web; usingSYSTEM.WEB.MVC; namespaceMVC filter. Filters {//Customizing a filter[Myactionfilter] Public classMyactionfilterattribute:actionfilterattribute {//overriding the OnActionExecuting method         Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {//Let's take a look at this filtercontext parameter: We know that the OnActionExecuting method is a way to trigger execution before the action executes, which means that in the future I write code here, Want to know if your onactionexecuting method is triggered by the action being invoked (because all the action methods are executed will trigger the OnActionExecuting filter method, So I just want to know exactly which action was executed when this onactionexecuting method is triggered)//gets the action name that triggers the current method (OnActionExecuting) (that is, the onactionexecuting that is triggered when the action method is executed (actionexecutingcontext Filtercontext))            stringActionName =FilterContext.ActionDescriptor.ActionName; //gets the controller name of the action that triggered the current method            stringControllername =FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName; //gets all the arguments of the action method that triggered the current method (because the parameter can have more than one, so it is a collection, and its return value type is idictionary<string,object> below in order to look good, with Var instead)            varPARAMSS =filtercontext.actionparameters; stringstr =""; if(PARAMSS. Any ())//any is to determine if the collection contains any elements, and returns False if the containing element returns true            {                  foreach(varKeyinchParamss. Keys)//the key to traverse it; (because we're going to get the name of the parameter s, so the traversal key){str= key +"the value is"+ Paramss[key];//Paramss[key] is the value of key                }              }                                //Gets the context of the current requestFilterContext.HttpContext.Response.Write ("Hello, I'm fine, too."); //Replace the return result view of the action method that triggered the current method with a Jsonresult (the return type of Filtercontext.result is Jsonresult)//Filtercontext.result: Gets or sets the result returned by the action method. (since we are getting or setting the return result of the action method, we can tamper with the return result of the action method that triggered the current method here .)//For example: The action method that triggers the current method is this: public ActionResult Add () {return Content ("China");} The return value of this action method is a "Chinese" text So here we can tamper with its return value by Filtercontext.result. Like this, I'm returning him a JSON .Jsonresult JSON=NewJsonresult (); Json. Data=New{status="1", message="OK"}; Json. Jsonrequestbehavior=Jsonrequestbehavior.allowget; Filtercontext.result=JSON; //Suppose we add a zone named admin to the MVC project, then add a home controller under the zone and add an index view. //So now we're going to go to the path to this view:http://localhost: 5219/admin/home/index//Get Zone            vararea = FilterContext.RouteData.DataTokens;//MVC can have a zone, and here's the one responsible for the storage area.//Get Zone name            varAreaName = area[" Area"];//this ["area"] was written dead. You can get the zone name based on ["area], because the key is fixed in the zone, so here the value of AreaName is admin//Routedata            varrd = Filtercontext.routedata;//Here you can get the control name, ation name, parameter name              varcontrolname = Rd. values["Controller"].              ToString (); varactname = Rd. values["Action"].                                                                       ToString (); }      }  }  

EntityFramework6.0 SQL read-write split Interceptor vs. MVC Action Interceptor

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.