我已经通过添加
创建了自定义规则 static partial void AddSharedRules()
{
RuleManager.AddShared<Tag>(
new CustomRule<String>(
"TagName",
"Invalid Tag Name, must be between 1 and 50 characters",
IsNullEmptyOrLarge));
}
到我的实体班。
然后我添加了规则(如视频所示,虽然视频已过时且信息错误):
public static bool IsNullEmptyOrLarge( string value )
{
return (value == null
|| String.IsNullOrEmpty(value)
|| value.Length > 50);
}
但现在我有了调用代码......
try
{
// some code
}
catch ( CodeSmith.Data.Rules… ??? )
{
// I can’t add the BrokenRuleException object. It’s not on the list.
}
我有:分配,安全和验证。
在PLINQO中捕获破坏的规则例外的正确方法是什么?
答案 0 :(得分:4)
以下是您需要做的事情,首先在项目中添加引用
System.ComponentModel.DataAnnotations
using CodeSmith.Data.Rules;
然后
try
{
context.SubmitChanges();
}
catch (BrokenRuleException ex)
{
foreach (BrokenRule rule in ex.BrokenRules)
{
Response.Write("<br/>" + rule.Message);
}
}
如果要更改默认消息,则可以转到实体并从
更改属性[Required]
到
[CodeSmith.Data.Audit.Audit]
private class Metadata
{
// Only Attributes in the class will be preserved.
public int NameId { get; set; }
[Required(ErrorMessage="please please please add a firstname!")]
public string FirstName { get; set; }
您还可以使用这些类型的数据注释属性
[StringLength(10, ErrorMessage= "The name cannot exceed 10 characters long")]
[Range(10, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Characters are not allowed.")]
public string FirstName { get; set; }
HTH