Click here to Skip to main content
15,881,089 members
Articles / Programming Languages / C#

Entity Framework and T4: Generate Query Objects on the Fl - Part 1

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
31 Jul 2011CPOL3 min read 20.2K   6   2
Generate Query Objects on the fly for your Entity Framework entities using T4 templates

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 been 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):

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

Instead of:

C#
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:

C#
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:

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.

C#
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:

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Italy Italy
My name is Rui Jarimba and I was born in Madeira island, Portugal and I currently live in Rome, Italy.

I have more than 10 years of experience developing software using the .NET Framework and other technologies (Web development, Databases, ...).

Some of my professional interests are: software development best practices, software architecture, cloud computing, Continuous Integration (CI), Continuous Delivery (CD) and agile methodologies such as Scrum, Kanban, Lean and any other methodology that can help me to become a better and more productive software engineer.

I believe in good code - code that is readable, maintainable, reusable, testable and deployable. This means that I'm not the "quick and dirty" type, I write code for the medium/long term whenever possible.

Something else about me - I love music, I am an amateur photographer, not a big fan of gyms (I prefer to do some outdoor activity such as walking/hiking), big foodie (I love Mediterranean cuisine and my glass of wine!).

Comments and Discussions

 
GeneralMy vote of 3 Pin
Rameshazsl25-Apr-12 0:41
Rameshazsl25-Apr-12 0:41 
GeneralRe: My vote of 3 Pin
Rui Jarimba9-May-12 7:14
professionalRui Jarimba9-May-12 7:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.