2011-05-25 157 views
0

可以說我有像這樣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。你是怎麼做到的?

謝謝!

回答

1

使用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"}); 
     } 
    } 
} 
+0

我增加了更多的代碼,以顯示真正的問題 - 獲取數據上下文到模型IValidateableObject。非常感謝,謝謝大家的回答。 – Micah 2011-05-25 15:10:22

+0

什麼是您的存儲庫架構?實體? – Mark 2011-05-26 20:36:01