如何检查角色列表中的角色?
How to check is Role in Roles list?
我需要检查角色是否在角色列表集合中,如果不在,则抛出验证结果。我如何比较这个或者我如何用其他方式解决这个问题?
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" });
}
}
您正在检查您的角色集合是否不是您的角色集合。而是检查 Rola
是否不在集合中。使用 Linq:
if(Roles.All(x => x != Rola ))
yield return new ValidationResult("Role isn't valid", new [] {nameof(Rola)};
我还建议像示例中那样使用 nameof
,这样如果您更改 属性 的名称,错误消息仍然有效。
我需要检查角色是否在角色列表集合中,如果不在,则抛出验证结果。我如何比较这个或者我如何用其他方式解决这个问题?
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" });
}
}
您正在检查您的角色集合是否不是您的角色集合。而是检查 Rola
是否不在集合中。使用 Linq:
if(Roles.All(x => x != Rola ))
yield return new ValidationResult("Role isn't valid", new [] {nameof(Rola)};
我还建议像示例中那样使用 nameof
,这样如果您更改 属性 的名称,错误消息仍然有效。