[英]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. 我想编写一个MSTest / nUnit测试来验证我的edmx模型中定义的所有存储过程和表在数据库上是否仍然有效。
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. 有一个庞大的开发团队,一些只在存储过程和c#中工作,我想运行集成测试来验证/验证项目中的EF模型。
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. 我在Linq2Sql中进行了测试,以查找存储过程调用中常见的属性,然后运行SQL查询以验证存储过程是否仍然存在。 I've now upgraded to EF6 and I want to keep a similar sanity check in the build.
我现在升级到EF6,我想在构建中保持类似的健全性检查。
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.
Schema返回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查询来获取其架构的所有过程,之后您可以将其与您的默认数据库对象集进行比较。 SQL query will be like that:
SQL查询将是这样的:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.