ASP.NET MVC验证架构DB验证值
问题描述:
可以说我有像这样ASP.NET MVC验证架构DB验证值
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"});
}
}
}
我增加了更多的代码,以显示真正的问题 - 获取数据上下文到模型IValidateableObject。非常感谢,谢谢大家的回答。 – Micah 2011-05-25 15:10:22
什么是您的存储库架构?实体? – Mark 2011-05-26 20:36:01