【问题标题】:Unable to create an object of type 'MarketContext'. For the different patterns supported at design time无法创建“MarketContext”类型的对象。对于设计时支持的不同模式
【发布时间】: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.DbContextOptions1[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.&lt;&gt;c__DisplayClass13_4.&lt;FindContextTypes&gt;b__13() --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.&lt;&gt;c__DisplayClass13_4.&lt;FindContextTypes&gt;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 }
                );
        }
    }

有人可以帮我吗?

【问题讨论】:

    标签: c# .net-core


    【解决方案1】:

    问题已解决,因为您提到在您的项目中add-migration 时发生错误

    也有这个问题。事实证明我在两者中都使用了IGetTransactionUseCase。因此出现了问题:

    builder.Services.AddTransient<IGetTransactionsUseCase, IGetTransactionsUseCase>();`
    

    GetTransactionUsecase后问题解决

    builder.Services.AddTransient<IGetTransactionsUseCase, GetTransactionsUseCase>();
    

    当我使用它时,它会显示错误:

    当我将其更改为图片中的高亮问题时,问题已解决,现在我的迁移已完成

    现在您看到我的迁移已成功更新

    【讨论】:

    • 我已经清理了你的代码。对你有好处,你解决了这个问题。但似乎提问者没有犯过类似的错误(见代码)。为什么你认为这是这个问题的答案?
    • 这是同一个问题,我解决了问题在于她的迁移,我改变了它
    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    相关资源
    最近更新 更多