我创建了ApplicationRole类并从IdentityRole 继承
using Microsoft.AspNetCore.Identity;
namespace ProjDAL.Entities
{
public class ApplicationRole : IdentityRole
{
}
}
当我尝试添加新角色时,我得到错误:
if (await _roleManager.FindByNameAsync("Quality Manager") == null)
{
await _roleManager.CreateAsync(new ApplicationRole("Quality Manager"));
}
"ApplicationRole"不包含接受参数1的构造函数。[DbInitialize]
更新:
我已经实现了构造函数:
public class ApplicationRole : IdentityRole
{
public ApplicationRole(string roleName) : base(roleName)
{
}
}
但现在出现错误:
System.InvalidOperationException: No suitable constructor found for entity
type 'ApplicationRole'. The following constructors had parameters that could
not be bound to properties of the entity type: cannot bind 'roleName'
in ApplicationRole(string roleName).
简短回答:将代码更改为以下
public class ApplicationRole : IdentityRole<string>
{
public ApplicationRole() : base()
{
}
public ApplicationRole(string roleName) : base(roleName)
{
}
}
长版本:
"ApplicationRole"不包含接受参数1的构造函数。[DbInitialize]`
发生第一个错误是因为您正试图通过创建新角色
new ApplicationRole("Quality Manager")
然而,没有一个构造函数接受单个字符串作为参数:
public class ApplicationRole : IdentityRole
{
}
所以它抱怨
不包含接受参数1的构造函数。[DbInitialize]
注意如果没有显式构造函数,C#将默认为您创建一个。
但是,如果您添加如下构造函数:
public class ApplicationRole : IdentityRole
{
public ApplicationRole(string roleName) : base(roleName)
{
}
}
只有一个构造函数接受string
作为roleName
。请注意,这意味着没有不带参数的构造函数。由于Identity
内部使用此构造函数(不带参数),因此它会抱怨No suitable constructor found for entity type 'ApplicationRole'
。
因此,如果您想通过以下方式创建ApplicationRole
:
new ApplicationRole("Quality Manager")
您需要同时创建ApplicationRole()
和ApplicationRole(string roleName)
构造函数。