Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How solve error ApplicationRole "does not contain a constructor that takes arguments 1. [DbInitialize]?

I creatred class ApplicationRole and inherited from IdentityRole

using Microsoft.AspNetCore.Identity;

namespace ProjDAL.Entities
{
    public class ApplicationRole : IdentityRole
    {

    }
}

When i trying add new roles i get error:

if (await _roleManager.FindByNameAsync("Quality Manager") == null)
{
    await _roleManager.CreateAsync(new ApplicationRole("Quality Manager"));
}

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

UPDATE:

I have implemented constructor:

public class ApplicationRole : IdentityRole
    {
        public ApplicationRole(string roleName) : base(roleName)
        {
        }
    }

but now get error:

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).
like image 558
Dmitrij Avatar asked Feb 08 '19 06:02

Dmitrij


1 Answers

Short Answer : Change your code as below

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

    public ApplicationRole(string roleName) : base(roleName)
    {
    }
}

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")

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

    public class ApplicationRole : IdentityRole
    {

    }

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

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'.

As a result, if you would like to create a ApplicationRole by:

new ApplicationRole("Quality Manager")

you need create both ApplicationRole() and ApplicationRole(string roleName) constructors.

like image 182
itminus Avatar answered Sep 27 '22 19:09

itminus