Um blog sobre nada

Um conjunto de inutilidades que podem vir a ser úteis

Archive for the ‘Entity Framework’ Category

Logging Queries on LINQ and EF

Posted by Diego on October 14, 2012


Instrumentation

 

Determine the running state of a system after it’s been deployed. Techniques:

·         Event logging

·         Debug tracing

·         Performance counters

 

 

 

1) Logging Queries

 

1.1) Accessing SQL Generated by LINQ to SQL

 

When working with LINQ to SQL classes, you can easily assign an object that inherits from TextWriter to the Log property of the DataContext object so that you can create a StreamWriter object that fills up a log file, assigns it to the Log property, and starts running queries.

The Log property is used on the DataContext object to capture all SQL statements when they are executed.

 

 

1)  Create the LinqToSqlTraceWriter.cs class:

 

using System;

using System.Diagnostics;

using System.Text;

using System.IO;

 

namespace AxiDataMerge.BLL

{

    public class LinqToSqlTraceWriter : TextWriter

    {

        private BooleanSwitch logSwitch;

        public LinqToSqlTraceWriter(string switchName)

        {

            logSwitch = new BooleanSwitch(switchName, switchName);

        }

        public override Encoding Encoding

        {

            get { throw new NotImplementedException(); }

        }

        public override void Write(char value)

        {

            if (logSwitch.Enabled)

            {

                Trace.Write(value);

            }

        }

        public override void Flush()

        {

            Trace.Flush();

        }

        public override void Close()

        {

            Trace.Close();

        }

    }

}

 

 

2)      Create the dbContext Object:

       MyDBDataContext context = new MyDBDataContext ();      

context.Log = new LinqToSqlTraceWriter("LinqToSqlSwitch");

 

 

3)  Enable on the web.config

 

<configuration>

       <system.diagnostics>

              <switches>

                     <add name="LinqToSqlSwitch" value="1"/>

              </switches>

       </system.diagnostics>

</configuration>

 

 

When you run the code to execute a LINQ to SQL query, you see the SQL statement in your Visual Studio .NET Output window because a default listener is configured that sets the trace output to the Output window

 

 

clip_image001

 

It can also be enhanced to write to text field:

<system.diagnostics>

       <switches>

              <add name="LinqToSqlSwitch" value="1"/>

       </switches>

       <trace autoflush="true">

              <listeners>

<add name="LinqToSql" initializeData="C:\Logs\CsLinqToSql.log" type="System.Diagnostics.TextWriterTraceListener"/>

              </listeners>

       </trace>            

</system.diagnostics>

 

 

1.2) Accessing SQL Generated by The Entity Framework

 

Do this by using the ToTraceString method on the generic ObjectQuery class. Most LINQ to Entities queries return a generic IQueryable object, which can be converted to a generic ObjectQuery class. To implement this, you can create an extension method for IQueryable that performs the conversion and executes the ToTraceString method.

The ToTraceString method retrieves the SQL for LINQ to Entities, and calling this method does not execute the query.

 

1)  Create the ExtensionMethods.cs class:

 

    public static class ExtensionMethods

    {

        public static string ToTraceString<T>(this IQueryable<T> query)

        {

            var objQuery = query as ObjectQuery<T>;

            if (objQuery != null)

                return string.Format("{0}{2}{1}{2}{2}", DateTime.Now, objQuery.ToTraceString(), Environment.NewLine);

            return string.Empty;

        }

    }

 

2)       Use it:

 

            var x = from acc in YourDBContext.YouEntity

                    select acc;

 

            string s = x.ToTraceString();

 

 

This will not execute the code, just get the query.

 

           

 

 

Posted in C#, Entity Framework, I.T. | Leave a Comment »

Entity Framework–how does Model First generate the database?

Posted by Diego on July 7, 2012

On the Model First approach, the database is created from your model. So basically you have your Entity Data Model (EDMX) which is represented by the Entity Data Model Designer (where you create your Entities and Associations) and Visual Studio generate the T-SQL script for you. But how does it do it? How do we go from an EDMX file to a .sql file with the DDL script for all objects?

First of all is good to say that Entity Framework uses the following 4 files, which I’ll refer only by name so forth:

· Entity Data Model (EDMX),

· Conceptual schema definition language (CSDL) – http://msdn.microsoft.com/en-us/library/bb399292.aspx

· Store schema definition language (SSDL)- http://msdn.microsoft.com/en-us/library/bb399559.aspx

· Mapping specification language (MSL) – http://msdn.microsoft.com/en-us/library/bb399202.aspx

 

From msdn:

The Entity Data Model Designer (Entity Designer) stores model and mapping information in an .edmx file at design time. At build time the Entity Designer uses the information in an .edmx file to create the .csdl, .ssdl, and .msl files that are needed by the Entity Framework at runtime.

Basically, it does by following a workflow, which is defined on the “Database Generation Workflow” property of the .edmx file.

The default value is TablePerTypeStrategy.xaml and the file is located on the path: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen

The file looks like this when open on VS:

clip_image002

As you can see, there are 2 activities, “CsdlToSsdlAndMslActivity” and “SsdlToDdlActivity” and what they do is pretty much explained on their names.

The first one (CsdlToSsdlAndMslActivity) reads the CSDL file and generates the SSDL and the MSL file that connect the two.

 

The second (SsdlToDdlActivity) generates DDL from the SSDL file by using a T4 template.
The template is stored in the same folder as the .xaml file and both of them can be graphically set on the Entity Data Model Designer:

clip_image004

What it basically does is provide a script that transforms SSDL into DLL.

Here is an example on how the tables are created:

clip_image006

Posted in C#, Entity Framework, I.T. | Leave a Comment »