Friday, December 28, 2012

Quick Test for Entity Framework DbContext

Okay, so I have been working on a project using Entity Framework, with reverse-engineered POCO classes and custom T4 template files. One of the things we were wanting to do is quickly identify an issues that caused by the generated entity and mapping classes.


One way to do this is to iterate through all the DbSet properties of the generated context and try to get some data. This proved to be tricky , but I did come up with something that I thought would be worth sharing with others. So here is the code that runs this basic test...
        
public void DbContextCheck()
{
    using (var myContext = new efDbContext())
    {

        var sets = from p in typeof(efDbContext).GetProperties()
                   where p.PropertyType.IsGenericType
                   && p.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>)
                   select p.GetValue(myContext, null);

         foreach (var myDbSet in sets)
         {
             IQueryable thisSet = (IQueryable)myDbSet;
             var myEnummerator = thisSet.GetEnumerator();
             myEnummerator.MoveNext();
         }

    }
}
Essentially, LINQ and a little reflection is used to get the instance of each IDbSet<TEntity> property. One of the things that I found interesting/frustrating, is that there is not a easy way to call the FirstOrDefault extension method for the DbSet. In order to get around this, each DbSet can be cast to an IQueryable type, since IDbSet, as well as DbSet have IQueryable in the inheritance chain. This allowed me to get the Enumerator for the DbSet and call the MoveNext method, to attempt to retrieve a record.

If something isn't quite right in the EF classes, this thing will blow up on you. Otherwise, it is an indication that  your EF stuff has generated properly, and you can code with confidence!

No comments:

Post a Comment