【问题标题】:How to check is Role in Roles list?如何检查角色列表中的角色?
【发布时间】:2019-10-19 21:08:47
【问题描述】:

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

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

【问题讨论】:

  • 可能需要用到:if(Roles.Contains(Role)).

标签: c# ivalidatableobject


【解决方案1】:

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

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

我还建议像示例中一样使用nameof,这样如果您更改属性名称,错误消息仍然有效。

【讨论】:

  • 我建议 !Roles.Any(x => x == Rola) 或 !Roles.Contains(Rola)
  • @Bart 除了个人的可读性偏好,你能解释一下Roles.All(x =&gt; x != Rola)!Roles.Contains(Rola) 之间的区别吗?你是说这个答案不完整?
  • @Archer 这只是个人喜好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 2021-12-07
  • 2016-06-21
  • 2022-12-24
  • 1970-01-01
  • 2013-03-31
  • 2021-02-24
相关资源
最近更新 更多