How do I write a test to verify Entity Framework Database First Model

I have a Entity Framework Database First Model.

I want to write a MSTest/nUnit test to verify that all the Stored procs and tables that are defined in my edmx model are still valid on the database.

With a large team of developers some only working on stored procedures and other in c# I would like to run an integration test to validate/verify the EF models in the project.

I had a test in Linq2Sql to look for an attribute that is common on the stored procedure calls then it ran a SQL Query to verify the stored procedure still exists. I've now upgraded to EF6 and I want to keep a similar sanity check in the build.

This is what I have so far.

 var list = context.MetadataWorkspace.GetItems<EntityType>(DataSpace.CSpace);

 var badSp = new List<string>();

 foreach (var table in list)
     if (!DoesTableExist(dbContext, table))

 if (badSp.Any())
            var retval = new StringBuilder();
            retval.AppendLine("The Following Objects do not exist in the database but do not exist the " + dbContext.GetType().Name + ".edmx, they may be obsolete");
    foreach (var sp in badSp)

Some issues I've come up with is this doesn't tell me if a table is in a different schema. Schema is returning null. I have tables in multiple schemas.

I also want to do a similar test to verify tables and views, they're in different schemas also.


I found the answer:

var list = context.MetadataWorkspace.GetItems<EdmFunction>(DataSpace.SSpace).Where(i=>i.ReturnParameter == null);

This returned the correct schema and stored procedure name. I then could call for each item in the list:

var sqlCommands = string.Format("SELECT 'x' FROM sys.objects WHERE object_id = OBJECT_ID(N'{0}') AND type in (N'P', N'PC')", storedProcedureName);
var exists = dbContext.Database.SqlQuery<string>(sqlCommands).Any();

You can use SQL query for get all of procedures with they schema, and after that you may compare this with you default set of database objects. SQL query will be like that:

FROM   sys.objects o
       INNER JOIN sys.schemas s
            ON  s.[schema_id] = o.[schema_id]
       INNER JOIN sys.[columns] c
            ON  c.[object_id] = o.[object_id]
       INNER JOIN sys.types t
            ON  t.system_type_id = c.system_type_id
                 AND t.user_type_id = c.user_type_id     

Need Your Help

Declaring a variable as a "Class" datatype, without calling the "Class" constructor?

c++ class constructor

Forgive me if I'm just blatantly missing something, but I'm trying to make the transition from structs and c to classes and c++.

Point of Sale and Inventory database schema

ruby-on-rails database-design point-of-sale inventory

I’m trying to create a basic Point of Sale and Inventory management system.