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

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;

The Model – MVC Music Store

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

Music Store Model

Using T4 to generate Query 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 query 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.

String properties, Datetimes and numeric values have some additional properties.

String properties

For a property named Name are generated the following properties in the query object:

  • Name
  • NameContains
  • NameStartsWith
  • NameEndsWith

Datetimes and numeric values

For Datetime and numeric properties (int, float, …) are generated range properties (excluding Primary and foreign key properties).

Assuming a property named Price the following properties are generated in the query object:

  • Price
  • PriceFrom
  • PriceTo

Associations

It’s also possible to search in an object’s association. You can access associations and their properties exactly the same way you do it when you’re using a model object (see the example above)

IQueryableObject<T>

All the objects implement the interface IQueryableObject<T>, where T is the respective entity. You can use any of those methods to query against your repositories.

public interface IQueryableObject<T> where T : class
{
    Func<T, bool> GetPredicate();
    Expression<Func<T, bool>> GetExpression();
    IQueryable<T> GetQuery(IQueryable<T> query);
}

Search model

This is the generated search model:

Search Model

Configuration

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

string inputFile = @"Model.edmx";
string namespaceName = @"MusicStore.Model"; 
string filenameSuffix = "Search.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] T4 (Text Template Transformation Toolkit) Code Generation – Best Kept Visual Studio Secret
http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx

[2] Code Generation and T4 Text Templates
http://msdn.microsoft.com/en-us/library/bb126445.aspx

[3] Query Object
http://www.martinfowler.com/eaaCatalog/queryObject.html

[4] LINQ to Entities: Combining Predicates
http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx

[5] Implementing ISession in EF4
http://geeksharp.com/2010/11/16/implementing-isession-in-ef4

Downloads

Download the demo project: MusicStore-T4.rar

About these ads

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

  1. Dear Rui Jarimba,

    You made my day. This is exactly what I was looking for. I am so glad I found your post.

    Thank you, Thank you, Thank you!

  2. Hi, I think your site might be having browser compatibility issues. When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, wonderful blog!

  3. Pingback: Entity Framework and T4: Generate Specification Objects for your entities | Rui Jarimba

  4. Hello, thanks for your example it is very interesting !
    Do you plan to do a “code first-friendly” version?

  5. Pingback: DotNetShoutout

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s