locked
No suitable constructor found for entity type 'Action'. The following parameters could not be bound to properties of the entity: 'object', 'method'. RRS feed

  • Question

  • User-234441352 posted

    When I try to run this command on Package Manager Console 

    Add-Migration AddedSecurityModule

    then I am getting following exception

    No suitable constructor found for entity type 'Action'. The following parameters could not be bound to properties of the entity: 'object', 'method'.

    Following is my tried code, please guide me.

    using DAL.Models;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using DAL.Core;
    using Manager.Interfaces;
    
    namespace DAL
    {
        public interface IDatabaseInitializer
        {
            Task SeedAsync();
        }
        public class DatabaseInitializer : IDatabaseInitializer
        {
            private readonly ApplicationDbContext _context;
            private readonly UserManager<ApplicationUser> _userManager;
            private readonly RoleManager<ApplicationRole> _roleManager;
            private readonly ILogger _logger;
    
            public DatabaseInitializer(ApplicationDbContext context,  ILogger<DatabaseInitializer> logger)
            {
               _context = context;
                _logger = logger;
            }
    
            public async Task SeedAsync()
            {
                await _context.Database.MigrateAsync().ConfigureAwait(false);
    
                if (!await _context.Users.AnyAsync())
                {
                    _logger.LogInformation("Generating inbuilt accounts");
    
                    const string adminRoleName = "power";
                    const string userRoleName = "ushr";
    
                    await EnsureRoleAsync(adminRoleName, "Default administrator", ApplicationPermissions.GetAllPermissionValues());
                    await EnsureRoleAsync(userRoleName, "Default user", new string[] { });                
    
                    await CreateUserAsync("adm", "pa", "rator", "ad@y.com", "+1 (123) 1212000", new string[] { adminRoleName });
                    await CreateUserAsync("usr", "pa", "Standard", "us@g.com", "+1 (123) 454-78787", new string[] { userRoleName });
    
                    _logger.LogInformation("Inbuilt account generation completed");
                }
    
              
                {
                    _logger.LogInformation("Seeding initial data");
    
                   await _context.SaveChangesAsync();
    
                    _logger.LogInformation("Seeding initial data completed");
                }
            }
    
            private async Task EnsureRoleAsync(string roleName, string description, string[] claims)
            {
                if ((await GetRoleByNameAsync(roleName)) == null)
                {
                    ApplicationRole applicationRole = new ApplicationRole(roleName, description);
    
                    var result = await CreateRoleAsync(applicationRole, claims);
    
                    if (!result.Item1)
                        throw new Exception($"Seeding \"{description}\" role failed. Errors: {string.Join(Environment.NewLine, result.Item2)}");
                }
            }
    
    
      public async Task<ApplicationRole> GetRoleByNameAsync(string roleName)
            {
                return await _roleManager.FindByNameAsync(roleName);
            }
    
       public async Task<Tuple<bool, string[]>> CreateRoleAsync(ApplicationRole role, IEnumerable<string> claims)
            {
               
               var result = await _roleManager.CreateAsync(role);
                if (!result.Succeeded)
                    return Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray());
                
                role = await _roleManager.FindByNameAsync(role.Name);
                return Tuple.Create(true, new string[] { });
            }
           
    
    public async Task<Tuple<bool, string[]>> CreateUserAsync(ApplicationUser user, IEnumerable<string> roles, string password)
            {
                var result = await _userManager.CreateAsync(user, password);
                if (!result.Succeeded)
                    return Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray());                    
    
                return Tuple.Create(true, new string[] { });
            }
    
            private async Task<ApplicationUser> CreateUserAsync(string userName, string password, string fullName, string email, string phoneNumber, string[] roles)
            {
                ApplicationUser applicationUser = new ApplicationUser
                {
                    UserName = userName,
                    FullName = fullName,
                    Email = email,
                    PhoneNumber = phoneNumber,
                    EmailConfirmed = true,
                    IsEnabled = true
                };
    
                var result = await _accountManager.CreateUserAsync(applicationUser, roles, password);
    
                if (!result.Item1)
                    throw new Exception($"Seeding \"{userName}\" user failed. Errors: {string.Join(Environment.NewLine, result.Item2)}");
    
    
                return applicationUser;
            }
        }
    }
    =============Startup.cs
    
    public void ConfigureServices(IServiceCollection services)
            {
    
     services.AddScoped<IAccountManager, AccountManager>();
    
     services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
    
     }
    
    ==============AccountController
    
     public class AccountController : Controller
        {
            private readonly IAccountManager _accountManager;
            public AccountController(IAccountManager accountManager)
            {
                _accountManager = accountManager;
            }
       }
    
    
    

    Friday, October 5, 2018 6:35 PM

Answers

  • User475983607 posted

    What you are doing or how you've configured the application is not clear.  If your DbContext is in project other than the main application, make sure the Package Manager Console default project is set to the assembly that has the DbContext.  Also set the solution startup project to the main web/api application.  The main app should have the configuration.

    I use the CLI and have multiple Contexts so my migration commands have the following format.

    dotnet ef migrations add MigrationName -c ApplicationDbContext -o Data/Migrations/ApplicationDb  --startup-project ../Namespace.Of.The.Assembly

    All I have to do is Change Directory to the DbContext assembly and run the command line.  Not need to remember setting the PMC configuration.

    But frankly, I really do not understand the code you're showing.   It looks like you are wrapping Identity APIs in another class which is a bit too much code for my liking.   Also I prefer to seed data using SQL in migrations.  I think it is much easier and straight forward but that's my opinion. 

    Anyway, see the following doc for guidance managing migration projects in VS.  Perhaps create a test project to get started.

    https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects

    Also see Google...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 5, 2018 7:24 PM
  • User-1764593085 posted

    Hi mehmoodahmed,

    Do you use asp.net core2.0 or 2.1? It seems that you have errors related to EF core. Have you tried to follow the error messages to add suitable constructor for the Action Entity?

    It is hard for us to reproduce the problem from current code snippet,could you share a simple demo to us? 

    You could also refer to the similar github issue here to find possible reasons.

    Xing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 8, 2018 7:03 AM
  • User-1764593085 posted

    Hi mehmoodahmed,

    I could reproduce your problem from your demo now. Why do you add System.Action type as navigation property in Permission.cs ? What would you like to get?

    public Action Action { get; set; }

    By removing it, add primary key and change your code like below I could add migrations successfully:

    services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"],
                    b => b.MigrationsAssembly("DAL")));

    Xing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 9, 2018 2:39 AM

All replies

  • User475983607 posted

    What you are doing or how you've configured the application is not clear.  If your DbContext is in project other than the main application, make sure the Package Manager Console default project is set to the assembly that has the DbContext.  Also set the solution startup project to the main web/api application.  The main app should have the configuration.

    I use the CLI and have multiple Contexts so my migration commands have the following format.

    dotnet ef migrations add MigrationName -c ApplicationDbContext -o Data/Migrations/ApplicationDb  --startup-project ../Namespace.Of.The.Assembly

    All I have to do is Change Directory to the DbContext assembly and run the command line.  Not need to remember setting the PMC configuration.

    But frankly, I really do not understand the code you're showing.   It looks like you are wrapping Identity APIs in another class which is a bit too much code for my liking.   Also I prefer to seed data using SQL in migrations.  I think it is much easier and straight forward but that's my opinion. 

    Anyway, see the following doc for guidance managing migration projects in VS.  Perhaps create a test project to get started.

    https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects

    Also see Google...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 5, 2018 7:24 PM
  • User-234441352 posted

    Hi, Thank you mgebhard,

    My DAL project have the following:

    1). ApplicationDbContext
    2). DatabaseInitializer
    3). Repositories and Models

    and Web.UI Project have the following:

    -> Migrations (ApplicationDbContextModelSnapshot and other migration files) 

                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"],
                    b => b.MigrationsAssembly("Web.UI")));
    services.AddScoped<IAccountManager, AccountManager>();


    // DB Creation and Seeding
    services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();

    See now I tried with the following cli command but getting the same error.


    dotnet ef migrations add AddedSecurityModule -c ApplicationDbContext -o Migrations/ApplicationDb --startup-project ../QuickApp.Pro

    System.InvalidOperationException: No suitable constructor found for entity type 'Action'. The following parameters could not be bound to properties of the entity: 'object', 'method'.
    at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConstructorBindingConvention.Apply(InternalModelBuilder modelBuilder)
    at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)
    at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder)
    at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()
    at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
    at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__1()
    at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
    at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
    at System.Lazy`1.CreateValue()
    at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
    at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
    at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
    at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
    at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
    at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
    at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
    at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
    at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
    at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
    at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
    at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
    No suitable constructor found for entity type 'Action'. The following parameters could not be bound to properties of the entity: 'object', 'method'.

    Sunday, October 7, 2018 11:35 AM
  • User-234441352 posted

    I just commented 

    IAccountManager from constructor of DatabaseInitializer and it stopped working.

      public DatabaseInitializer(ApplicationDbContext context, 
                /*IAccountManager accountManager,*/ ILogger<DatabaseInitializer> logger)
            {
                //_accountManager = accountManager;
                _context = context;
                _logger = logger;
            }

    Sunday, October 7, 2018 12:17 PM
  • User475983607 posted
    Try reading the links in the previous post.
    Sunday, October 7, 2018 12:21 PM
  • User-1764593085 posted

    Hi mehmoodahmed,

    Do you use asp.net core2.0 or 2.1? It seems that you have errors related to EF core. Have you tried to follow the error messages to add suitable constructor for the Action Entity?

    It is hard for us to reproduce the problem from current code snippet,could you share a simple demo to us? 

    You could also refer to the similar github issue here to find possible reasons.

    Xing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 8, 2018 7:03 AM
  • User-234441352 posted


    Thank you zing zou and mgebhard,
    Yes I am trying to fix now.i am using core 2.1.I am uploading some sample application. appology due to the large size of the application , I am excluding the files.
    But hopefully I am sure when you 'll see my code.You 'll get to know that what I am trying to do.I just want to find the issue in this structure to add new or upgrade the migrations. Please see now at https://1drv.ms/u/s!AitLVJhHEke3gpgn68MDSFzI7wc_UA
    thanks
    Monday, October 8, 2018 8:17 PM
  • User-1764593085 posted

    Hi mehmoodahmed,

    I could reproduce your problem from your demo now. Why do you add System.Action type as navigation property in Permission.cs ? What would you like to get?

    public Action Action { get; set; }

    By removing it, add primary key and change your code like below I could add migrations successfully:

    services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"],
                    b => b.MigrationsAssembly("DAL")));

    Xing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 9, 2018 2:39 AM
  • User-234441352 posted


    Thank you for pointing out the issue, Yes xing, it can be the issue because of implicit types. I have this entity at my database side. I tried to change it now.

    Issue has been resolved. Now I am able to run the migration commands.

    thank you

    Tuesday, October 9, 2018 2:46 AM