Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test Entity Framework Code First Mappings?

I'm using Code First to map classes to an existing database. I need a way to unit test these mappings, which are a mix of convention-based, attribute-based, and fluent-api.

To unit test, I need to confirm that properties of the classes map to the correct table and column names in the database. This test needs to be performed against the context, and should cover all configuration options for code first.

At a very high level, I'd be looking to assert something like (pseudo-code):

Assert.IsTrue(context.TableFor<Widget>().IsNamed("tbl_Widget"));
Assert.IsTrue(context.ColumnFor<Widget>(w => w.Property).IsNamed("WidgetProperty"));
like image 353
STW Avatar asked Apr 25 '12 20:04

STW


1 Answers

Another idea to consider is using Linq and ToString().

For eaxample this :

context.Widget.Select(c => c.Property).ToString()

Will result in this for SQL Server Provider :

"SELECT [Var_3].[WidgetProperty] AS [WidgetProperty] FROM [dbo].[Widget]..."

Now we could hide it all in some Extension method that and parses resulting SQL it would look almost like Your pseudo-code :

Assert.IsTrue(context.Widgets.GetSqlColumnNameFor(w => w.Property).IsNamed("WidgetProperty"));

Draft for extension :

public string GetSqlColumnNameFor<TSource>(this DbSet<T> source, Expression<Func<TSource, TResult>> selector)
{
    var sql = source.Select(selector).ToString();

    var columnName = sql... // TODO : Some regex parsing

    return 
       columnName;
}

Similary we could create GetSqlTableNameFor().

UPDATE : I decided to look for some dedicates SQL Parsers, so this solution is more generic, obviously there is such a thing for .NET :

http://www.dpriver.com/blog/list-of-demos-illustrate-how-to-use-general-sql-parser/generate-internal-query-parse-tree-in-xml-for-further-processing/

like image 169
Edgars Pivovarenoks Avatar answered Sep 20 '22 15:09

Edgars Pivovarenoks