问题描述
||
可以说我有一个像这样的课程
public class Blog{
[Key]
public int ID{get;set;}
//these can only be tags that are in the tags db table
IEnumerable<string> Tags{get;set;}
//validation pseudocode to illustrate issue
public bool IsValid() {
//this is my issue-- how do i get my db context/repository
//into my validation logic for this class? i need it
var goodTags=db.Tags.Select(i=>i.Name);
//if this tag isn\'t a \"goodTag\",then this shouldnt validate
Tags.ForEach(i=> {
if(!goodTags.Contains(i))
return false;
});
}
}
如何在不将数据访问逻辑放入模型的情况下,验证标签中包含的字符串是否在标签数据库表中?我正在使用MVC3。你是怎么做到的?
谢谢!
解决方法
使用IInvalidatableObject进行自我验证,如下所示:
public Class Blog : IValidatableObject
{
[Key]
public int Id {get; set;}
public ICollection<string> Tags {get; set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(!Tags.Contains(\"testString\"))
{
yield return new ValidationResult(\"Not a valid tag.\",new [] {\"Tags\"});
}
}
}