c# - 如何解决错误 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).
解决方案
简短答案:如下更改您的代码
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
asroleName
。请注意,这意味着没有不带参数的构造函数。由于Identity
内部使用此构造函数(不带参数),因此它抱怨No suitable constructor found for entity type 'ApplicationRole'
.
因此,如果您想ApplicationRole
通过以下方式创建:
new ApplicationRole("Quality Manager")
您需要同时创建ApplicationRole()
和ApplicationRole(string roleName)
构造函数。
推荐阅读
- python - IBM DB2 重启后无法从 PYTHON 访问数据库
- ios - 当缓冲区包含交错音频时,AVAudioFile.write(from:) 失败
- presto - Presto SQL 中 TO_CHAR() 的替代语法是什么?
- php - 如何在 PHP 中找到 2 维数组中的元素数?
- php - PHP IP 白名单
- java - 我可以直接将来自外部源的数据映射到数据库上吗?
- python - 在python中获取一个变量在函数外工作
- arrays - 程序输出比数组中实际元素数多 1
- unity3d - unity 如何组合每个对象名称?
- java - 如何从 class.getResource() 释放资源