Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

asp.net mvc - I got an error while uploading the seed data?

In a .net core project, I got this error from seed data attachments and could not solve it. I would be glad if you could help.

"*System.InvalidOperationException: '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.' *

Below is my startup file, seed file and DbContext file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BuyfiletBusiness.Abstract;
using BuyfiletBusiness.Concrete;
using BuyfiletData.Abstract;
using BuyfiletData.Concrete.EfCore;
using BuyfiletEntity.bagla;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace BuyfiletWeb
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; } 

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ShopContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:SqlConStr"].ToString(),
                o =>
                {
                    o.MigrationsAssembly("BuyfiletData");
                }));
            services.AddIdentity<UserEntity, IdentityRole>().AddEntityFrameworkStores<ShopContext>().AddDefaultTokenProviders(); 
            services.AddScoped<IProductRepository, EfCoreProductRepository>();
            services.AddScoped<IProductService, ProductManager>();
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                SeedDatabase.Seed();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

using AlisverisagiEntity;
using AlisverisagiEntity.EntityModels;
using BuyfiletData.Concrete.EfCore.Seeds;
using BuyfiletEntity.bagla;
using BuyfiletEntity.EntityModels.Category;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace BuyfiletData.Concrete.EfCore
{
    public class ShopContext:IdentityDbContext<UserEntity>
    {
        public ShopContext()
        {

        }
        public ShopContext(DbContextOptions<ShopContext> options) : base(options)
        {
        }
        public DbSet<UserEntity> UserModels { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<BasicCategory> Categories { get; set; }
        public DbSet<MainCategory> MainCategories { get; set; }
        public DbSet<SubCategory> SubCategories { get; set; }
        public DbSet<UserEntity> UserEntities { get; set; }
        public DbSet<Childs> Childs { get; set; }
        public DbSet<Grandchilds> Grandchilds { get; set; }
     

      

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ProductCategory>().HasKey(c => new
            {c.BasicCategoryId, c.ProductId,c.MainCategoryId,c.SubCategoryId}); 
            
            
        
           
        

        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using AlisverisagiEntity.EntityModels;
using BuyfiletEntity.EntityModels.Category;

namespace BuyfiletData.Concrete.EfCore
{
   public static class SeedDatabase
    {
        public static void Seed()
        {
            var context = new ShopContext();
            context.Products.AddRange(products);
            context.SaveChanges();
        }

        private static Product[] products =
        {
            new Product()
            {
                Id = 1, StockCode = "5484959", Label = "Samsung S6", Status = 1,
                Brand = "Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili)", IsOptionedProduct = 1,
                IsOptionOfAProduct = 2400, MarketPrice = 2600, BuyingPrice = "2400", Price = 2400, Tax = 14,
                CurrencyAbbr = "tl", RebateType = 1, Rebate = 200, MoneyOrder = 300, StockAmount = 5, StockType = "cm",
                Warranty = 200,
                Picture1Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture2Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture3Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture4Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture5Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture6Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Dm3 = 2554,
                Details =
                    "Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili",
                Point = 15.8, Variety = "k?rm?z?", Size = "25", Color = "siyah", Gender = "erkek",
            },
            new Product()
            {
                Id = 2, StockCode = "5465465456", Label = "Samsung S6", Status = 1,
                Brand = "Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili)", IsOptionedProduct = 1,
                IsOptionOfAProduct = 2400, MarketPrice = 2600, BuyingPrice = "2400", Price = 2400, Tax = 14,
                CurrencyAbbr = "tl", RebateType = 1, Rebate = 200, MoneyOrder = 300, StockAmount = 5, StockType = "cm",
                Warranty = 200,
                Picture1Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture2Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture3Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture4Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture5Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture6Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Dm3 = 2554,
                Details =
                    "Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili",
                Point = 15.8, Variety = "k?rm?z?", Size = "25", Color = "siyah", Gender = "erkek",
            },
            new Product()
            {
                Id = 3, StockCode = "5484959", Label = "Samsung S6", Status = 1,
                Brand = "Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili)", IsOptionedProduct = 1,
                IsOptionOfAProduct = 2400, MarketPrice = 2600, BuyingPrice = "2400", Price = 2400, Tax = 14,
                CurrencyAbbr = "tl", RebateType = 1, Rebate = 200, MoneyOrder = 300, StockAmount = 5, StockType = "cm",
                Warranty = 200,
                Picture1Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture2Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture3Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture4Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture5Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Picture6Path = new Uri("https://productimages.hepsiburada.net/s/43/550/10756209672242.jpg/format:webp"),
                Dm3 = 2554,
                Details =
                    "Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili Samsung Galaxy M51 128 GB (Samsung Türkiye Garantili",
                Point = 15.8, Variety = "k?rm?z?", Size = "25", Color = "siyah", Gender = "erkek",
            }
        };
    }
}

enter image description here

question from:https://stackoverflow.com/questions/65646952/i-got-an-error-while-uploading-the-seed-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's clearly that you instantiate a new instance of ShopContext using its parameterless constructor and it really does not have any OnConfiguring code. Hence the error.

In the context of Startup.Configure method, you can obtain the configured ShopContext correctly via the IApplicationBuilder like this:

if (env.IsDevelopment())
{
  using(var sc = app.ApplicationServices.CreateScope())
  using(var dbContext = sc.ServiceProvider.GetRequiredService<ShopContext>())
  {
      //check if database does not exist
      //we do this one time only to avoid Seed is run each time debugging
      if(!dbContext.Database.CanConnect()){
        //for testing only, do not use for production because then 
        //you usually need a true migration.
        dbContext.Database.EnsureCreated();
        SeedDatabase.Seed(dbContext);
      }   
  }            
  app.UseDeveloperExceptionPage();
}

Modify your SeedDatabase.Seed method to accept a ShopContext instead:

public static void Seed(ShopContext context)
{
   context.Products.AddRange(products);
   context.SaveChanges();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...