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

China☆狼群 提交于 2019-12-13 05:11:04

问题


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))
     {
       badSp.Add(table.Name);
     }
 }

 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");
            badSp.Sort();
    foreach (var sp in badSp)
    {
       retval.AppendLine(sp);
    }
    Assert.Fail(retval.ToString())  
}

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.


回答1:


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();



回答2:


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:

SELECT o.name
      ,o.[type]
      ,o.type_desc
      ,s.name
      ,c.name
      ,t.name
      ,c.max_length
      ,c.precision
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     


来源:https://stackoverflow.com/questions/19847192/how-do-i-write-a-test-to-verify-entity-framework-database-first-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!