In this post we will be discussing about how to log database commands and queries sent to the database from the Entity Framework. Its always better to log whatever activities you are doing on your database to find out any suspicious activities. We will show the simplest example how to log database commands and queries using Entity Framework 6.
We will be using Log method of Database class which is to log the SQL generated by the System.Data.Entity.DbContext to the given delegate. You can also change the format of the log text by creating a new formatter. You can see the log in various different ways i.e. either you can save the log into a file or you can trace that into an output window etc.
Lets first write code to trace the Command Log into the output window as shown below :
In the above code we are tracing the log which will logs all the activities performed by Entity Framework e.g. opening & closing connection, execution & completion time and database queries and commands as shown below :
If you want to append a log into a text file then you will change the code as shown below
Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.
We will be using Log method of Database class which is to log the SQL generated by the System.Data.Entity.DbContext to the given delegate. You can also change the format of the log text by creating a new formatter. You can see the log in various different ways i.e. either you can save the log into a file or you can trace that into an output window etc.
Lets first write code to trace the Command Log into the output window as shown below :
db.Database.Log = log => Trace.Write(log); if (ModelState.IsValid) { db.Transactions.Add(transaction); db.SaveChanges(); } return View();
In the above code we are tracing the log which will logs all the activities performed by Entity Framework e.g. opening & closing connection, execution & completion time and database queries and commands as shown below :
If you want to append a log into a text file then you will change the code as shown below
db.Database.Log = log => File.AppendText("Log_File_Path").WriteLine(log);
Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.
Related articles
- Finally .Net is becoming Open Source and Cross Platform
- Asp Net Interview Questions and Answers - Part 2
- How to Get Latest Tweets of a particular HashTag using Nodejs
- Fetching Twitter Trends by places in Node.js
- How to fetch trending tweets in Nodejs
- Top 4 Optimization tips in Entity Framework for Dot Net Applications
- How to solve Unable to update database in ASP.NET MVC
- Coding Defined: Get list of modified objects in Entity Framework : C#
- LoopBack - NodeJS API Framework
- How to create Simple JavaScript CLI with Node.js
No comments:
Post a Comment