Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A provider can be configured by overriding the DbContext.OnConfiguring

For some reason since I added a Application User class ,it says I have two contexts which I do not but I created the class as follows as it said to do so:

public class ApplicationDbContextFactory : IDbContextFactory<solitudeDContext>
    {
        public solitudeDContext Create(DbContextFactoryOptions options)
        {
            var optionsBuilder = new DbContextOptionsBuilder<solitudeDContext>();
            return new solitudeDContext(optionsBuilder.Options);
        }
    }
}

But now it is saying the following:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

This is my db context layer:

public class solitudeDContext : IdentityDbContext<IdentityUser>
    {  public solitudeDContext(DbContextOptions<solitudeDContext> options) : base(options)
        {
        }
        public DbSet<basketheader> BasketHeader { get; set; }
        public DbSet<basketlines> BasketLines { get; set; }
        public DbSet<customer> Customer { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<ApplicationUser>(entity =>
            {
                entity.ToTable(name: "AspNetUser", schema: "Security");
                entity.Property(e => e.Id).HasColumnName("AspNetUserId");

            });

        }
    }

Anyone know what is up here? I am using ASP.NET CORE 1.1. Before I used my own Application user for Identy and this compiled fine. So I enclose it below in case something is wrong there.

public  class ApplicationUser: IdentityUser
{
        public string FirstName { get; set; }
        public string LastName{ get; set; }
        public DateTime dob { get; set; }
}

My startup.cs:

 // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddDbContext<IdentityDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),b=>b.MigrationsAssembly("solitudeeccore")));
        services.AddIdentity<IdentityUser, IdentityRole>()
   .AddEntityFrameworkStores<IdentityDbContext>()
   .AddDefaultTokenProviders();
        services.AddTransient<IMessageService, FileMessageService>();
        services.AddAuthentication();            
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();                
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseIdentity();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });


    }

My only guess is that now because I am using Application User Identity, user is making donet compiler thinking two contexts ?

like image 521
david Avatar asked Jul 29 '17 17:07

david


People also ask

What is services AddDbContext?

AddDbContext<TContext>(IServiceCollection, Action<DbContextOptionsBuilder>, ServiceLifetime) Registers the given context as a service in the IServiceCollection. You use this method when using dependency injection in your application, such as with ASP.NET.

How do I create a database context in .NET core?

To have a usable Entity Framework DBContext, we need to change the configuration of the application. We will need to add a connection string so that our DBContext knows which server to go to and which database to query. We will put the connection string in a JSON configuration file.


1 Answers

I suggest you fixing this by adding IDesignTimeDbContextFactory implementation.

// TODO: Remove.
// (part of the workaround for https://github.com/aspnet/EntityFramework/issues/5320)
public class TemporaryDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build();

        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();

        var connectionString = configuration.GetConnectionString("DefaultConnection");

        builder.UseSqlServer(connectionString);

        // Stop client query evaluation
        builder.ConfigureWarnings(w => 
            w.Throw(RelationalEventId.QueryClientEvaluationWarning));

        return new ApplicationDbContext(builder.Options);
    }
}
like image 191
Nikolay Kostov Avatar answered Sep 30 '22 05:09

Nikolay Kostov