[英]How do I stop this error when creating a new Role Provider?
I'm trying to add a new Role Provider into my MVC5 project - however on the "return roles.ToArray();" 我试图在我的MVC5项目中添加一个新的角色提供程序-但是在“返回角色.ToArray();”上 line I get the error:
行我得到错误:
Cannot implicitly convert type 'wb.Models.UserRole[]' to 'string[]'
public override string[] GetRolesForUser(string username)
{
var roles = db.UserRole
.Where(x => x.UserName
.Equals(username, StringComparison.CurrentCultureIgnoreCase));
if (roles != null)
return roles.ToArray();
else
return new string[] { }; ;
}
Can anyone suggest how I correct this please? 有人可以建议我如何纠正此问题吗?
You are returning an array of roles, not role names. 您将返回一组角色,而不是角色名称。 Select out the names and return them as an array.
选择名称并将它们作为数组返回。
public override string[] GetRolesForUser(string username)
{
var roleNames =
db.UserRole
.Where(x => x.UserName.Equals(username,
StringComparison.CurrentCultureIgnoreCase))
.Select(x => x.RoleName);
if (roleNames.Count() > 0)
return roleNames.ToArray();
else
return new string[] { }; ;
}
The problem in your code is in the following line: 您的代码中的问题在以下行中:
roles.ToArray();
This returns an array of wb.Models.UserRole
instead of an array of strings, string[]
. 这将返回
wb.Models.UserRole
数组,而不是字符串数组string[]
。 One option I see, it would be before the call of ToArray()
to select an anonymous type with one string property, which would contain the information you want. 我看到的一个选项是,在调用
ToArray()
之前选择具有一个字符串属性的匿名类型,该属性将包含所需的信息。 Something like this: 像这样:
var roles = db.UserRole
.Where(x => x.UserName
.Equals(username, StringComparison.CurrentCultureIgnoreCase))
.Select(x => x.RoleName);
I am not sure if your class has a property called RoleName
, but in general terms you should project the results of your query like above, in a sequence of strings. 我不确定您的类是否具有一个名为
RoleName
的属性,但总的来说,您应该按照一系列字符串的方式投影查询的结果。 Then calling ToArray
will create an array of strings and you would be more than done. 然后调用
ToArray
将创建一个字符串数组,您会做的不止这些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.