如何解决上传种子数据时出错?
在 .net 核心项目中,我从种子数据附件中收到此错误,但无法解决。如果您能提供帮助,我会很高兴。
"*system.invalidOperationException: '没有为此 DbContext 配置数据库提供程序。可以通过覆盖 'DbContext.OnConfiguring' 方法或在应用程序服务提供程序上使用'AddDbContext' 来配置提供程序。如果使用了“AddDbContext”,然后还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 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",new Product()
{
Id = 3,}
};
}
}
解决方法
很明显,您使用其无参数构造函数实例化了 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
方法以接受 ShopContext
:
public static void Seed(ShopContext context)
{
context.Products.AddRange(products);
context.SaveChanges();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。