0

我需要检查角色是否在角色列表集合中,如果不是,则抛出验证结果。我该如何比较这个或者我该如何解决这个问题?

public class UserViewModel:IValidatableObject
{
    [Required]
    public string Username { get; set; }
    public IEnumerable<string> Roles { get; set; }

    [Required]
    public string Rola { get; set; }

    public UserViewModel()
    {
        Repozytorium db = new Repozytorium();
        Roles = db.GetAllRoles();
    }
    public UserViewModel(string userName, string rola)
    {
        Repozytorium db = new Repozytorium();
        Roles = db.GetAllRoles();
        Username = userName;
        Rola = rola;
    }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Roles != Roles )   //this dont work 
            yield return new ValidationResult("role isnt valid", new string[] { "Rola" });
    }
}
4

1 回答 1

1

您正在检查您的角色集合是否不是您的角色集合。而是检查Rola不在集合中。使用 Linq:

if(Roles.All(x => x != Rola ))
    yield return new ValidationResult("Role isn't valid", new [] {nameof(Rola)}; 

另外我建议nameof在示例中使用 like ,这样如果您更改属性的名称,错误消息将保持有效。

于 2019-06-04T10:38:14.233 回答