首页 > 解决方案 > 如何解决错误 ApplicationRole “不包含带参数 1. [DbInitialize] 的构造函数?

问题描述

我创建了类 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).

标签: c#asp.net-coreasp.net-identity

解决方案


简短答案:如下更改您的代码

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)
    {
    }
}

只有一个构造函数接受stringasroleName。请注意,这意味着没有不带参数的构造函数。由于Identity内部使用此构造函数(不带参数),因此它抱怨No suitable constructor found for entity type 'ApplicationRole'.

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

new ApplicationRole("Quality Manager")

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


推荐阅读