Entity Framework 6.0 Tutorials (4): Database Command Logging

Source: Internet
Author: User

Database Command Logging:

In this section, you'll learn how to log commands & queries sent to the database by Entity Framework.

Prior to EF 6, we used the database tracing tool or third party tracing utility to trace database queries and commands Sen T by Entity Framework. Now, the EF 6 provides a simple mechanism to log everything this Entity Framework is doing. It logs all of the activity performed by EF using context.database.Log

You can attach any method of any class, which accepts one string parameter and returns void.

In the following example, we use Console.Write method to log EF activities:

using (varnew  schooldbentities ()) {    = console.write;     var student = context. Students                        "Student1"). Firstordefault<student>();     " edited Name " ;    Context. SaveChanges ();}

Output:

You can see in the output so it logs all the activities performed by EF, e.g. opening & closing connection, Executio N & Completion time and database queries & commands.

Context.Database.Log is a action<string> so, can attach any method which have one string parameter and void return type. For example:

 Public classlogger{ Public Static voidLog (stringmessage) {Console.WriteLine ("EF Message: {0}", message); }}classef6demo{ Public Static voiddbcommandlogging () {using(varContext =Newschooldbentities ()) {context. Database.Log=Logger.Log; varStudent =context. Students. Where (S= = S.studentname = ="Student1"). Firstordefault<student>(); Student. Studentname="edited Name"; Context.            SaveChanges (); }        }}

Download DB First sample project for DB command logging demo.

Entity Framework 6.0 Tutorials (4): Database Command Logging

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.