Entity Framework: Get mapped table name from an entity

Extension methods for ObjectContext and DbContent to get the mapped table name from an entity.

Table of contents

The problem

I am working on a set of extension methods to perform a bulk insert using Entity Framework, using internally the SqlBulkCopy object. One of the steps involved is to get the mapped table name from an entity. After some google searching, I found a post on StackOverflow that led me to the solution.

The solution

The trick is to use the method ObjectQuery.ToTraceString to generate a SQL Select statement for an entity, and then extract the table name from that statement.

Let’s assume that you have an entity named Album corresponding to a table named dbo.Albums.

// context is ObjectContext
string sql = context.CreateObjectSet<T>().ToTraceString();

...

The generated SQL for that entity can be something like this:

SELECT 
[Extent1].[AlbumId] AS [AlbumId], 
[Extent1].[GenreId] AS [GenreId], 
[Extent1].[ArtistId] AS [ArtistId], 
[Extent1].[Title] AS [Title], 
[Extent1].[Price] AS [Price], 
[Extent1].[AlbumArtUrl] AS [AlbumArtUrl]
FROM [dbo].[Albums] AS [Extent1] 

So, all we need to do is to parse the SELECT statement to get the table name. This is the approach used in the post above but it has some limitations – that code will work only for tables that are in the default SQL Server schema (dbo.{tableName}). I made some changes to that code and I’m extracting the full table name using regular expressions.

The extension methods

I have created one extension method for DbContext and other for ObjectContext:

public static class ContextExtensions
{
    public static string GetTableName<T>(this DbContext context) where T : class
    {
        ObjectContext objectContext = ((IObjectContextAdapter) context).ObjectContext;

        return objectContext.GetTableName<T>();
    }

    public static string GetTableName<T>(this ObjectContext context) where T : class
    {
        string sql = context.CreateObjectSet<T>().ToTraceString();
        Regex regex = new Regex("FROM (?<table>.*) AS");
        Match match = regex.Match(sql);

        string table = match.Groups["table"].Value;
        return table;
    }
}

Using the code

Getting the mapped table name for an entity named Album, using a ObjectContext object:

ObjectContext context = ....;
string table = context.GetTableName<Album>();

Or using a DbContext object:

DbContext context = ....;
string table = context.GetTableName<Album>();

References

Technorati Tags: ,

Entity Framework and T4: Generate Specification Objects for your entities

Learn how to use Specification Pattern and how to generate Specification Objects for your Entity Framework entities using T4 templates.

Table of contents

Specification Pattern Overview

According to Martin Fowler and Eric Evans, a specification define a set of conditions that a candidate object must fulfill in order to meet the specification. Specifications can be used for:

  • Selection: When you need to select a set of objects based on some criteria
  • Validation: when you need to check that only suitable objects are used for a certain purpose

The Specification Pattern can be represented like this in .NET (using generics):

public interface ISpecification<T> where T : class
{
    Expression<Func<T, bool>> GetExpression();
    bool IsSatisfiedBy(T entity);
}

We can also create Composite Specifications by combining other specifications – this allow us to reuse existing specifications to create more complex ones.

Using Specification Pattern

I’m using the MVC Music Store database, this is the model:

Music Store Model
And now some examples. I will assume that you have a repository like this (I’m using this implementation):

public IQueryable All<T>(Expression<Func<bool, T>> expression) where T : class

A generic Specification class

public class Specification<T> : ISpecification<T> where T : class
{
    private Expression<Func<T, bool>> expression;

    public Expression<Func<T, bool>> GetExpression()
    {
        return expression;
    }

    public Specification(Expression<Func<T, bool>> expression)
    {
        this.expression = expression;
    }

    public bool IsSatisfiedBy(T entity)
    {
        var query = (new[] { entity }).AsQueryable();

        return query.Any(this.expression);
    }
}

Creating specifications

Using the generic class to create specifications:

  • One specification for jazz albums
  • One specification for cheap albums (price between 1 and 10)
public static ISpecification<Album> JazzAlbumSpecification
{
	get
	{
		return new Specification<Album>(
			x => x.Genre.Name == "Jazz"
		);
	}
}

public static ISpecification<Album> CheapAlbumSpecification
{
	get
	{
		return new Specification<Album>(
			x => x.Price >= 1 && x.Price <= 10
		);
	}
}

Selecting objects

var albums = from x in repository.All<Album>(JazzAlbumSpecification.GetExpression())
             select x;

Performing validation

Album metalAlbum = GetMetalAlbum();
Album jazzAlbum = GetJazzAlbum();

bool isJazzAlbum = JazzAlbumSpecification.IsSatisfiedBy(metalAlbum); 
isJazzAlbum = JazzAlbumSpecification.IsSatisfiedBy(jazzAlbum);

Composing specifications

Existing specifications can be combined to form more complex ones. Using these extension methods it’s easy to create composite specifications (see this article to understand how to combine lambda expressions):

public static ISpecification<T> And<T>(this ISpecification<T> first, ISpecification<T> second) where T : class
{
    return new Specification<T>(
        first.GetExpression()
        .And(second.GetExpression())
    );
}

public static ISpecification<T> Or<T>(this ISpecification<T> first, ISpecification<T> second) where T : class
{
	return new Specification<T>(
        first.GetExpression()
        .Or(second.GetExpression())
    );
}

The specifications defined above can now be combined to compose a new specification like this:

ISpecification<Album> cheapJazzAlbumSpecification = JazzAlbumSpecification.And(CheapAlbumSpecification);

// using the specification to select all cheap jazz albums
var cheapJazzAlbums = from x in repository.All<Album>(cheapJazzAlbumSpecification.GetExpression())
                      select x;

Using T4 to generate Specification Objects

T4 is a code generator built right into Visual Studio. You can generate any text file using T4 templates: C#, javascript, HTML, XML and many others. If you’ve never heard about it, this is a good place to start:

T4 (Text Template Transformation Toolkit) Code Generation – Best Kept Visual Studio Secret

I’ve created a T4 template that generates automatically all the Specification Objects, one for each entity in our model. All the generated objects have all the public properties of their respective entities, including association properties. All objects were marked with the [Serializable] attribute, so you can easily serialize it if you need.

In a previous article I’ve created query objects for Entity Framework, I’m generating exactly the same properties in this template. You can see a complete description of the generated properties here.

This is the generated object model:


The previous specifications can now be written like this:

public static ISpecification<Album> JazzAlbumSpecification
{
    get
    {
        return new AlbumSpecification() {
            Genre = new GenreSpecification() { Name = "Jazz" }
        };
    }
}

public static ISpecification<Album> CheapAlbumSpecification
{
    get
    {
        return new AlbumSpecification() {
            PriceFrom = 1,
            PriceTo = 10
        };
    }
}

Configuration

In the demo solution double-click ModelSpecification.tt and change the following lines, according to your needs:

string inputFile = @"Model.edmx";
string namespaceName = @"MusicStore.Model";
string filenameSuffix = "Specification.gen.cs";

When you save the template file or you rebuild the project the code will be regenerated. If you don’t want to generate the code, remove the value of the Custom Tool property in the property browser of the template file (by default the value is TextTemplatingFileGenerator).

References

[1] Specification Pattern

[2] Specification (Martin Fowler/Eric Evans)

[3] T4 (Text Template Transformation Toolkit) Code Generation – Best Kept Visual Studio Secret

[4] LINQ to Entities: Combining Predicates

[5] Implementing ISession in EF4

Downloads

Download the demo project: MusicStore-T4-Specification.rar


Entity Framework and T4: Generate Query Objects on the fly, part 1

Generate Query Objects on the fly for your Entity Framework entities using T4 templates. Don’t worry about LINQ, let the objects do all the work for you.

Table of contents

  • Configuration
  • References
  • Downloads
  • I’ve read some stuff about T4 templates in the last 2-3 years, but only recently I decided to give it a try. My first attempt was to generate Query Objects for Entity Framework, that’s what I’ll talk about in this article – what’s their purpose and how to use them.

    In part 2 I’ll create a demo ASP.NET MVC application that uses query objects created with this template. I already have another T4 template that creates javascript objects for my entities, and I’m developing a custom ASP.NET view template for those objects.

    Many thanks to Colin Meek [4], his work has really helpful.

    What is a Query Object?

    A Query Object is an object that represents a database query [1]:

    A Query Object is an interpreter [Gang of Four], that is, a structure of objects that can form itself into a SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place.

    Assuming that you have a repository like this (I’m using this implementation):

    public IQueryable All<T>(Expression<Func<bool, T>> expression) where T : class
    

    Instead of:

    var albuns = from x in repository.All<Album>()
                     where x.Artist.Name == "Metallica"
                     && x.Genre.Name.Contains("Metal")
                     && x.Price >= 5 && x.Price
                     select x;
    

    You can do this way:

    var search = new AlbumSearch();
    search.PriceFrom = 5;
    search.PriceTo = 10;
    search.Artist = new ArtistSearch(){ Name = "Metallica" };
    search.Genre = new GenreSearch(){ NameContains = "Metal" };
    
    var albuns = from x in repository.All<Album>(search.GetExpression())
                      select x;
    

    Continue reading