用于数据库验证值的ASP.NET MVC验证体系结构

问题描述

|| 可以说我有一个像这样的课程
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\"});
        }
    }
}  
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...