views:

378

answers:

1

Hi guys

I have been looking at the following and it would appear that there are great benefits to be gained by using compiled queries... http://blogs.msdn.com/ricom/archive/2008/01/14/performance-quiz-13-linq-to-sql-compiled-query-cost-solution.aspx

My problem is that I want to unit test my queries, but compiled queries need a concrete instance of a class that derives from DataContext (which is particularly difficult to mock out)... Thus I have come up with the following code and I was wondering if any knows whether I should still get the performance benefits of compiled queries...

private static readonly Func<IDatabase, IActionParameters, ISportProgramMapper, IQueryable<ISportProgram>> _GetQueryUnCompiled =
    (db, parameters, mapper) => from x in db.SportProgramDataSource.ThatHaveActiveSports()
                                where x.SportProgramId == parameters.Id
                                select mapper.FromDataToEntity(x);

private static readonly Func<Database, IActionParameters, ISportProgramMapper, IQueryable<ISportProgram>> _GetQuery = CompiledQuery.Compile<Database, int, ISportProgramMapper, IQueryable<ISportProgram>>((db, parameters, mapper) => _GetQueryUnCompiled(db, parameters, mapper));

public IActionResult<ISportProgram> Get(IActionParameters parameters)
{
    Check.Argument("parameters").ThatValue(parameters).IsNotNull();

    IDatabase db = this.CreateDatabase(); 
    ISportProgramMapper mapper = this.CreateMapper<ISportProgramMapper>();
    Database typedDb = db as Database;

    var result = typedDb != null ? _GetQuery(typedDb, parameters, mapper).FirstOrDefault() : _GetQueryUnCompiled(db, parameters, mapper).FirstOrDefault();

    return this.CreateActionResult(result);
}

Note in a unit test scenario my db wont be of type Database which means it will call the uncompiled version, in a prod scenario it will be of type Database and will run the compiled version.

Cheers Anthony

Update: Ok even if I do refactor the code so that my method which is currently in the DAL uses a repository that returns an IQueryable the underlying question still remain, the version of the repository that uses the compiled queries would wrap a version that contains the raw query, in a similar fashion to what I am doing at the moment... with the pattern of having the _GetQuery call _GetQueryUnCompiled do I still get a performance benefit??

+1  A: 

Just a thought, can you refactor to use IEnumerable<> only by layering? This way you can test you DB code separately from your queries?

Preet Sangha
Yeap- why does a unit test need to know about DataContext at all. Mine certainly don't.
RichardOD