1

I've created default DB context as I do always and tried to add migration. I got an error:

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

My DB Context:

public class DataContext : IdentityDbContext<User, ApplicationRole, Guid>
{
    public DataContext(DbContextOptions<DataContext> opts) : base(opts) { }


    public DbSet<User> Users { get; set; }

    public DbSet<Coach> Coaches { get; set; }

    public DbSet<Coaching> Coachings { get; set; }

    public DbSet<CoachingVideo> CoachingVideos { get; set; }

    public DbSet<AppFile> Files { get; set; }
}

My DB Context injection (already in Program.cs)

public static class DataContextExtension
{
    public static IServiceCollection AddDataContext(this IServiceCollection services, IConfiguration builder)
    {
        services.AddDbContext<DataContext>(
                o => o.UseSqlServer(builder.GetConnectionString("DefaultConnection")));
        return services;
    }
}

I tried to install different versions, but nothing...

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32

1 Answers1

1

First, make sure the connection string is correct

Then use this code

services.AddDbContext<DataContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

or

services.AddDbContext<DataContext>(options =>
            {
                options.UseSqlServer("Conection string");
            });

If the above code does not work , use this code section 1

public DataContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        if (!options.IsConfigured)
        {
            options.UseSqlServer("CONNECTION STRING");
        }
    }

If the above code does not work, disable your code temporarily and enter this code and after updating the database, comment this code and activate your code.

//public DataContext(DbContextOptions options) : base(options)
  //  {
   // }

protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        
      options.UseSqlServer("CONNECTION STRING");
        
    }

abolfazl sadeghi
  • 2,277
  • 2
  • 12
  • 20