How to: Trace SQL Statements Generated by OpenAccessContext

Telerik Data Access has an integrated mechanism for tracing and logging the communication between the application and the database server. In order to use the tracing and logging mechanism of the OpenAccessContext, you should initialize the OpenAccessContext's Log property.

C#


    using (EntitiesModel dbContext = new EntitiesModel())
    {
       dbContext.Log = new StringWriter();
    }

VB.NET


    Using dbContext As New EntitiesModel()
     dbContext.Log = New StringWriter()
    End Using

In the following example Load, Insert and Update operations are performed. Finally, the OpenAccessContext's SaveChanges method is invoked. Note that a new StringWriter instance is created and set to the OpenAccessContext's Log property.

C#


    System.IO.StringWriter output = new System.IO.StringWriter();
    using (EntitiesModel dbContext = new EntitiesModel())
    {
       dbContext.Log = output;

       // Load
       Customer customer = dbContext.Customers.First(c => c.CustomerID == "ALFKI");

       // Update
       customer.Fax = "[newFax]";

       // Insert
       Customer newCustomer = new Customer();
       newCustomer.CustomerID = "MyId";
       newCustomer.CompanyName = "MyCompany";

       dbContext.Add(newCustomer);
       dbContext.SaveChanges();

       Console.Write(output.ToString());
       Console.Read();
    }

VB.NET


    Dim output As New IO.StringWriter()
    Using dbContext As New EntitiesModel()
     dbContext.Log = output

     ' Load
     Dim _customer As Customer = dbContext.Customers.First(Function(c) c.CustomerID = "ALFKI")

     ' Update
     _customer.Fax = "[newFax]"

     ' Insert
     Dim newCustomer As New Customer()
     newCustomer.CustomerID = "MyId"
     newCustomer.CompanyName = "MyCompany"

     dbContext.Add(newCustomer)
     dbContext.SaveChanges()

     Console.Write(output.ToString())
     Console.Read()
    End Using

Finally, the result of the output.ToString() method should be similar to this:

SQL


    SELECT  TOP(??T) a.[CustomerID] AS COL1, a.[Address] AS COL2, a.[City] AS COL3, a.[CompanyName] AS COL4, a.[ContactName] AS COL5, a.[ContactTitle] AS COL6, a.[Country] AS COL7, a.[Fax] AS COL8, a.[Phone] AS COL9, a.[PostalCode] AS COL10, a.[Region] AS COL11 FROM [Customers] a WHERE a.[CustomerID] = 'ALFKI'

    INSERT INTO [Customers] ([Address], [City], [CompanyName], [ContactName], [ContactTitle], [Country], [CustomerID], [Fax], [Phone], [PostalCode], [Region]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

    UPDATE [Customers] SET [Fax]=? WHERE [CustomerID] = ? AND [Fax]=?

See Also