【发布时间】:2021-12-01 00:45:42
【问题描述】:
执行时我无法进行迁移
dotnet ef migrations add initial --verbose
我得到了这个错误:
未找到应用服务提供商。 在项目中查找 DbContext 类... 找到 DbContext 'MarketContext'。 Microsoft.EntityFrameworkCore.Design.OperationException:无法创建“MarketContext”类型的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728 ---> System.InvalidOperationException:无法解析类型'Microsoft.EntityFrameworkCore.DbContextOptions
1[Plugins.DataStore.SQL.MarketContext]' while attempting to activate 'Plugins.DataStore.SQL.MarketContext'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13() --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13() at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1工厂的服务) 在 Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(字符串 contextType) 在 Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(字符串名称、字符串 outputDir、字符串 contextType、字符串命名空间) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(字符串名称,字符串 outputDir,字符串 contextType,字符串命名空间) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.c__DisplayClass0_0.<.ctor>b__0() 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0() 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)*
程序.cs
public class Program
{
public static void Main(string[] args)
=> CreateHostBuilder(args).Build().Run();
// EF Core uses this method at design time to access the DbContext
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
webBuilder => webBuilder.UseStartup<Startup>());
}
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, IServiceProvider serviceProvider)
{
Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
var test = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MarketContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString(Configuration.GetConnectionString("DefaultConnection")));
//options.UseSqlServer("Server =localhost; Database = Supermarket; Trusted_Connection = True;");
});
// services.AddDbContext<MarketContext>();
//Injecao de Dependencia para in Memory
services.AddScoped<ICategoryRepository, CategoryInMemoryRepository>();
services.AddScoped<IProductRepository, ProductsInMemoryRepository>();
services.AddScoped<ITransactionRepository, TransactionInMemoryRepository>();
//Injecao de Dependencia para UseCases and Repositories
services.AddTransient<IViewCategoriesUseCase,ViewCategoriesUseCase>();
services.AddTransient<IAddCategoryUseCase, AddCategoryUseCase>();
services.AddTransient<IEditCategoryUseCase, EditCategoryUseCase>();
services.AddTransient<IGetCategoryByIdUseCase, GetCategoryByIdUseCase>();
services.AddTransient<IDeleteCategoryUseCase, DeleteCategoryUseCase>();
services.AddTransient<IViewProductsUseCase, ViewProductsUseCase>();
services.AddTransient<IAddProductUseCase, AddProductUseCase>();
services.AddTransient<IEditProductUseCase, EditProductUseCase>();
services.AddTransient<IGetProductByIdUseCase, GetProductByIdUseCase>();
services.AddTransient<IDeleteProductUseCase, DeleteProductUseCase>();
services.AddTransient<IViewProductsByCategoryId, ViewProductsByCategoryId>();
services.AddTransient<ISellProductUseCase, SellProductUseCase>();
services.AddTransient<IRecordTransactionUseCase, RecordTransactionUseCase>();
services.AddTransient<IGetTodayTransactionsUseCase, GetTodayTransactionsUseCase>();
services.AddTransient<IGetTransactionsUseCase, GetTransactionsUseCase>();
}
// 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())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/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.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
MyDbContext
public class MarketContext : DbContext
{
public MarketContext(DbContextOptions<MarketContext> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Transaction> Transactions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>()
.HasMany(c => c.Products)
.WithOne(p => p.Category)
.HasForeignKey(p => p.CategoryId);
//seeding some data
modelBuilder.Entity<Category>().HasData(
new Category
{
CategoryId = 1,
Name = "Beverage",
Description = "Beverage"
},
new Category
{
CategoryId = 2,
Name = "Bakery",
Description = "Bakery"
},
new Category
{
CategoryId = 3,
Name = "Meate",
Description = "Meat"
}
);
modelBuilder.Entity<Product>().HasData(
new Product { ProductId = 1, CategoryId = 1, Name = "Chá Gelado", Quantity = 100, Price = 1.99 },
new Product { ProductId = 2, CategoryId = 1, Name = "Cerveja", Quantity = 200, Price = 3.99 },
new Product { ProductId = 3, CategoryId = 2, Name = "Pao Integral", Quantity = 200, Price = 1.50 },
new Product { ProductId = 4, CategoryId = 2, Name = "Pao Frances", Quantity = 200, Price = 1 }
);
}
}
有人可以帮我吗?
【问题讨论】: