我正在尝试为数据库项目创建自定义代码分析。我为目前工作正常的表编写了几个验证。但是,我对视图的第一次验证似乎不起作用。在调试规则时,它实际上只会进入一次规则。那时ruleExecutionContext.ModelElement为null。除了视图类型类之外,我一直在寻找另一个类,但这似乎是正确使用的类。我目前正在使用此版本的SSDT:SSDT_14.0.61021.0_EN以及Visual Studio 2015.我完全不知道为什么表测试工作,但视图没有。
[ExportCodeAnalysisRule(NestedViewRule.RuleId,
NestedViewRule.RuleDisplayName,
Description = NestedViewRule.RuleDisplayName,
Category = Constants.Performance,
RuleScope = SqlRuleScope.Model)]
public sealed class NestedViewRule : SqlCodeAnalysisRule
{
public const string RuleId = Constants.RuleNameSpace + "SRP0001";
public const string RuleDisplayName = "Views should not use other views as a data source";
public const string Message = "View {0} uses view {1} as a datasource. This has a negative impact upon performance.";
public NestedViewRule()
{
SupportedElementTypes = new[] { ModelSchema.View }; // View.TypeClass, neither seems to work
}
public override IList<SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext)
{
List<SqlRuleProblem> problems = new List<SqlRuleProblem>();
TSqlObject sqlObj = ruleExecutionContext.ModelElement;
if (sqlObj != null)
{
foreach (var child in sqlObj.GetReferenced(DacQueryScopes.All).Where(x => x.ObjectType == View.TypeClass))
{
string msg = string.Format(Message, RuleUtils.GetElementName(ruleExecutionContext, sqlObj), RuleUtils.GetElementName(ruleExecutionContext, child));
problems.Add(new SqlRuleProblem(msg, sqlObj) /*{ Severity = SqlRuleProblemSeverity.Error } */);
}
}
return problems;
}
}
以下是我目前正在使用的表格规则之一,以防任何人感兴趣:
[ExportCodeAnalysisRule(TableHasPrimaryKeyRule.RuleId,
TableHasPrimaryKeyRule.RuleDisplayName,
Description = TableHasPrimaryKeyRule.RuleDisplayName,
Category = Constants.BestPractice,
RuleScope = SqlRuleScope.Element)]
public sealed class TableHasPrimaryKeyRule : SqlCodeAnalysisRule
{
public const string RuleId = Constants.RuleNameSpace + "SRB0002";
public const string RuleDisplayName = "Tables should have a primary key.";
public const string Message = "Table {0} does not have a primary key.";
public TableHasPrimaryKeyRule()
{
SupportedElementTypes = new[] { ModelSchema.Table };
}
public override IList<SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext)
{
List<SqlRuleProblem> problems = new List<SqlRuleProblem>();
TSqlObject sqlObj = ruleExecutionContext.ModelElement;
if (sqlObj != null)
{
var child = sqlObj.GetChildren(DacQueryScopes.All).FirstOrDefault(x => x.ObjectType == PrimaryKeyConstraint.TypeClass);
if (child == null)
{
string msg = string.Format(Message, RuleUtils.GetElementName(ruleExecutionContext, sqlObj));
problems.Add(new SqlRuleProblem(msg, sqlObj));
}
}
return problems;
}
}
答案 0 :(得分:3)
好的,我道歉,但在发布之后,我注意到我使用RuleScope = SqlRuleScope.Model进行视图检查,并使用Element for the Tables。然后我推断出这会强制忽略视图注册的访问者模式,并且模型一次性传递给我。
使用RuleScope = SqlRuleScope.Element更改属性以匹配表检查修复了问题。