Entity Framework or EF Core is a lightweight, could be extended, and a cross-platform version of the commonly known Entity Framework data access technology.
EF Core is an object-relational mapper (O/RM) that allows .NET developers to work with a database that uses .NET objects. It removes the need for much of the data-access code which developers usually require to write codes. EF Core supports several database engines.
Presently, Entity Framework Core yet does not have all of the attributes provided by pre-Core versions. One of the features is an ability to intercept questions, something which was offered by the IDbCommandInterceptor, IDbCommandTreeInterceptor interfaces.
The EF Core 2.0 has an interception at the SQL level, and you can only get to this in a rather complicated way, via the DiagnosticSource mechanism. Here we shall discuss on how to create a class with two methods, as shown below:
Public class CommandListener
public void OnCommandExecuting(DbCommand command, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime)
public void OnCommandExecuted(object result, bool async)
You will require the Microsoft.Extensions.DiagnosticAdapter NuGet package to assemble this.
The methods can be hooked to EF Core as shown below:
var listener = ctx.GetService();
(listener as DiagnosticListener).SubscribeWithAdapter(new CommandListener());
Here, ctx is a DbContext, and it is being tried to access its registered DiagnosticSource service, which is a DiagnosticListener. You need to add a subscriber, and that’s it!
From the OnCommandExecuted method you can summon these methods whatever you choose, as long you keep the [DiagnosticName] features, the result parameter would contain either a scalar, a number or a RelationalDataReader object a sync, and would tell you exactly what version of the method was implemented.
OnCommandExecuting is quite amazing because there you can get an access to the DbCommand which is on how to implement the SQL command and can edit its SQL or parameters.
There are other mechanisms of interception as well, like the IQuerySqlGenerator and IQueryCompiler, to be covered later.
With this, we conclude. Keep coding!
If you want to enhance yourself in basics and concepts with Dot Net Course and improve yourself through Dot NET training program; our institute would be of great help and support.
We give a well-structured program for the best Dot Net Course. Among several good institutes of dot net training and placement in Pune, CRBtech has created a niche for itself.
Code source: Development With A Dot