Home > Blockchain >  ASP.NET Core 6.0 - Entity Framework error migrations
ASP.NET Core 6.0 - Entity Framework error migrations

Time:01-31

I am making an APIS system in ASP.NET Core 6.0 with Entity Framework for the creation of models in the database. When trying to do the migrations, I get this error:

Unable to create an object of type 'RtvcContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728`

To clarify, that link that tells me in the error I already visited it, and copy and paste the code as it says, I leave you the code of my project:

My Program.cs class:

using RtvcApi;

public class Program
{
    public static void Main(string[] args)
        => CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args)
        => Host.CreateDefaultBuilder(args)
               .ConfigureWebHostDefaults(
                webBuilder => webBuilder.UseStartup<Startup>());
}

My Startup.cs class:

using Infrastructure.EntityFramework;
namespace RtvcApi;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();
        //services.AddDbContext<RtvcContext>();
        services.AddApplicationServices();
        services.AddInfrastructureServices(configuration);
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }
}

My configuration classes - AddApplicationServices:

namespace RtvcApi;

public static class ApplicationServiceRegistration
{
    public static IServiceCollection AddApplicationServices(this IServiceCollection Services) 
    {
        Services.AddAutoMapper(Assembly.GetExecutingAssembly());
        Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
        Services.AddMediatR(Assembly.GetExecutingAssembly());
 
        Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));
        Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));

        return Services;
    }
}

AddInfrastructureServices.cs:

namespace Infrastructure.EntityFramework;

public static class InfrastructureServiceRegistration
{
    public static IServiceCollection AddInfrastructureServices(this IServiceCollection services,     IConfiguration configurations)
    {
        String ConnectionString = configurations.GetConnectionString("DefaultConnection");
        services.AddDbContext<RtvcContext>(opt =>
        {
            opt.UseMySql(
                ConnectionString,
                ServerVersion.AutoDetect(ConnectionString)
            );
        });

        services.AddScoped(typeof(IAsyncRepository<>), typeof(IRepositoryBase<>));
        services.AddScoped<IEntityRepository, MySQLEntityRepository>();

        services.Configure<EmailSetting>(c => configurations.GetSection("EmailSettings"));
        services.AddScoped<IEmailService, EmailService>();

        return services;
    }
}

Now in the Infrastructure layer, which is where I have the context with the configurations, the code is the following:

rtvcContext.cs :

namespace Infrastructure.EntityFramework;

public class RtvcContext : DbContext
{
    public RtvcContext(DbContextOptions<RtvcContext> options) : base(options)
    {
    } 

    public DbSet<RtvcEntity> Entitys { get; set; }
    public DbSet<EntityType> EntitysTypes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        try
        {
            base.OnModelCreating(modelBuilder);

            // ENTITIES
            modelBuilder.ApplyConfiguration(new EntityConfiguration());
            modelBuilder.ApplyConfiguration(new EntityTypeConfiguration());
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        configurationBuilder.Properties<decimal>()
            .HavePrecision(22, 2);

        configurationBuilder.Properties<string>()
            .HaveColumnType("varchar(255)");
    }
}

EntityConfiguration.cs:

namespace Infrastructure.EntityFramework.Configurations;

public class EntityConfiguration : IEntityTypeConfiguration<Entity>
{
    public void Configure(EntityTypeBuilder<Entity> modelBuilder)
    {
        modelBuilder.ToTable("entidades");

        modelBuilder.HasKey(x => x.Id);

        modelBuilder.Property(x => x.EntityTypeId)
                    .IsRequired()
                    .HasDefaultValue(0)
                    .HasColumnName("entidadTipoId");
        modelBuilder.HasIndex(x => x.EntityTypeId);

        modelBuilder.Property(x => x.CreatedAt)
                    .HasColumnName("FechaActualizado")
                    .HasDefaultValue(DateTime.MinValue);
        modelBuilder.Property(x => x.UpdateAt)
                    .HasColumnName("FechaActualizado")
                    .HasDefaultValue(DateTime.MinValue);

        modelBuilder.Property(x => x.Email)
                    .HasColumnName("correoElectronico")
                    .HasDefaultValue("");
        modelBuilder.Property(x => x.Name)
                    .HasColumnName("correoElectronico")
                    .HasDefaultValue("");
        modelBuilder.Property(x => x.LastName)
                    .HasColumnName("correoElectronico")
                    .HasDefaultValue("");
        modelBuilder.Property(x => x.NumberPhone)
                    .HasColumnName("correoElectronico")
                    .HasDefaultValue("");
    }
}

EntityTypeConfiguration:

namespace Infrastructure.EntityFramework.Configurations;

public class EntityTypeConfiguration : IEntityTypeConfiguration<Entity>
{
    public void Configure(EntityTypeBuilder<Entity> modelBuilder)
    {
        modelBuilder.ToTable("entidades_tipos");

        modelBuilder.HasKey(e => e.Id);

        modelBuilder.Property(e => e.Name)
                    .HasDefaultValue("")
                    .HasColumnName("Nombre");
    }
}

I hope I have been clear and that someone can help me with this because I can't think of what it could be, thanks!

I was trying to do migrations and it is throwing me the error that I mentioned in the query, I don't know what it could be, I hope someone can help me, thank you very much in advance!

More specific mistake

No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'RtvcContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'RtvcContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Infrastructure.EntityFramework.RtvcContext]' while attempting to activate 'Infrastructure.EntityFramework.RtvcContext'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
   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, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.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)

Also add the database contextoptions class, the code is as follows: DataBaseContextOptions.cs:

  public class DataBaseContextOptions : IDesignTimeDbContextFactory<RtvcContext>
    {
        public RtvcContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
    
            var builder = new DbContextOptionsBuilder<RtvcContext>();
            String ConnectionString = configuration.GetConnectionString("DefaultConnection");
            builder.UseMySql(
                ConnectionString,
                 ServerVersion.AutoDetect(ConnectionString));
    
            return new RtvcContext(builder.Options);
        }
    }

CodePudding user response:

I fixed it with the following command:

dotnet ef migrations add InitialCreate -s RtvcApi -p Infrastructure -v --context RtvcContext

dotnet ef database update -s RtvcApi -p Infrastructure -v --context RtvcContext

  • Related