我正在撰写一个C#单元测试,用于验证ORM类的字符串属性与目标数据库(始终为SQL 2008)以及数据映射到的类是否匹配。
检查指定外键在数据库中是否有效很容易:
static private bool ConstraintExsits(string table, string column, ConstraintType constraintType)
{
string constraintTypeWhereClause;
switch (constraintType)
{
case ConstraintType.PrimaryKey:
constraintTypeWhereClause = "PRIMARY KEY";
break;
case ConstraintType.ForeignKey:
constraintTypeWhereClause = "FOREIGN KEY";
break;
default:
throw new ArgumentOutOfRangeException("constraintType");
}
var cmd = new SqlCommand(
@"SELECT a.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS a
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE b on a.CONSTRAINT_NAME = b.CONSTRAINT_NAME
WHERE a.TABLE_NAME = @table AND b.COLUMN_NAME = @column AND a.CONSTRAINT_TYPE = '" + constraintTypeWhereClause + "'",
Connection);
cmd.Parameters.AddWithValue("@table", table.Trim('[').Trim(']'));
cmd.Parameters.AddWithValue("@column", column.Trim('[').Trim(']'));
return !string.IsNullOrEmpty((string)cmd.ExecuteScalar());
}
现在看以下外键关系图:
![alt text](https://lh4.ggpht.com/_4Ug1wDoP8aw/SvfxF8Dx0vI/AAAAAAAAADc/9QU3JOs3I5Q/FK.gif)
谢谢 J