首页 > 解决方案 > 上传种子数据时出错?

问题描述

在 .net 核心项目中,我从种子数据附件中收到此错误,无法解决。如果您能提供帮助,我会很高兴。

"* System.InvalidOperationException: '没有为此 DbContext 配置数据库提供程序。可以通过覆盖 'DbContext.OnConfiguring' 方法或在应用程序服务提供程序上使用 'AddDbContext' 来配置提供程序。如果使用 'AddDbContext',然后还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。 *

下面是我的启动文件、种子文件和 DbContext 文件。

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",
            }
        };
    }
}

在此处输入图像描述

标签: asp.net-mvcasp.net-core.net-coreentity-framework-core

解决方案


很明显,您ShopContext使用其无参数构造函数实例化了一个新实例,它实际上没有任何OnConfiguring代码。因此错误。

Startup.Configure方法的上下文中,您可以ShopContext通过以下方式正确获取配置IApplicationBuilder

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();
}

修改您的SeedDatabase.Seed方法以接受 aShopContext代替:

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

推荐阅读