如何解决错误 ApplicationRole“不包含采用参数 1. [DbInitialize] 的构造函数?

Dmi*_*rij 4 c# asp.net-identity asp.net-core

我创建了类 ApplicationRole 并继承自 IdentityRole

using Microsoft.AspNetCore.Identity;

namespace ProjDAL.Entities
{
    public class ApplicationRole : IdentityRole
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试添加新角色时,出现错误:

if (await _roleManager.FindByNameAsync("Quality Manager") == null)
{
    await _roleManager.CreateAsync(new ApplicationRole("Quality Manager"));
}
Run Code Online (Sandbox Code Playgroud)

'ApplicationRole“不包含带参数 1 的构造函数。[DbInitialize]

更新:

我已经实现了构造函数:

public class ApplicationRole : IdentityRole
    {
        public ApplicationRole(string roleName) : base(roleName)
        {
        }
    }
Run Code Online (Sandbox Code Playgroud)

但现在得到错误:

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).
Run Code Online (Sandbox Code Playgroud)

itm*_*nus 9

Short Answer : Change your code as below

public class ApplicationRole : IdentityRole<string>
{
    public ApplicationRole() : base()
    {
    }

    public ApplicationRole(string roleName) : base(roleName)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

Long Version :

'ApplicationRole "does not contain a constructor that takes arguments 1. [DbInitialize]`

The first error occurs because you're trying to create a new role by

new ApplicationRole("Quality Manager")
Run Code Online (Sandbox Code Playgroud)

However, there's no constructor that accepts a single string as parameter:

    public class ApplicationRole : IdentityRole
    {

    }
Run Code Online (Sandbox Code Playgroud)

So it complains that

does not contain a constructor that takes arguments 1. [DbInitialize]

Note when there's no explicit constructor, C# will create one by default for you.

However, if you add a constructor as below :

public class ApplicationRole : IdentityRole
{
    public ApplicationRole(string roleName) : base(roleName)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

There will be only one constructor which accepts a string as roleName. Note that means there is no constructor that takes no arguments. As this constructor (that takes no arguments) is used by the Identity internally, it complains that No suitable constructor found for entity type 'ApplicationRole'.

因此,如果您想ApplicationRole通过以下方式创建:

new ApplicationRole("Quality Manager")
Run Code Online (Sandbox Code Playgroud)

您需要同时创建ApplicationRole()ApplicationRole(string roleName)构造函数。