How to check is Role in Roles list?

319 Views Asked by At

I need to ckeck if Role is in Roles list collection, if isnt, throw validation result. How can i compare this or how can i solve this other way?

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" });
    }
}
1

There are 1 best solutions below

3
aksu On BEST ANSWER

You are checking if your role collection is not your role collection. Instead check that the Rola is not in the collection. With Linq:

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

Also I recommend using nameof like in the example so that if you change the name of the property, the error message stays valid.