添加迁移问题(EntityFrameworkCore)

问题描述 投票:0回答:1

尝试为代码优先数据库添加迁移,但出现错误

无法创建“StoreContext”类型的对象。

这是带有 -verbose 的错误消息:

System.InvalidOperationException:尝试激活“КПО_лаб_2._3.StoreContext”时,无法解析类型“Microsoft.EntityFrameworkCore.DbContextOptions`1[КПО_лаб_2._3.StoreContext]”的服务。 在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider 提供程序) 在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider 提供程序,类型 instanceType,Object[] 参数) 在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider 提供程序,类型类型) 在 Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.b__13() 内部异常堆栈跟踪结束 ---

这是我的上下文代码:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace КПО_лаб_2._3
{
    public class StoreContext : DbContext
    {
        public DbSet<Client> Clients { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }

        public StoreContext(DbContextOptions<StoreContext> options) : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=localhost;Database=Store;Integrated Security=True;TrustServerCertificate=Yes;Trusted_Connection=True");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Настройка связей между сущностями

            // Связь "Клиент" (Client) - "Заказ" (Order) (1-*)
            modelBuilder.Entity<Order>()
                .HasOne(o => o.Client)
                .WithMany(c => c.Orders)
                .HasForeignKey(o => o.ClientId);

            // Связь "Заказ" (Order) - "Детали заказа" (OrderDetail) (1-*)
            modelBuilder.Entity<OrderDetail>()
                .HasOne(od => od.Order)
                .WithMany(o => o.OrderDetails)
                .HasForeignKey(od => od.OrderId);

            // Связь "Товар" (Product) - "Детали заказа" (OrderDetail) (1-*)
            modelBuilder.Entity<OrderDetail>()
                .HasOne(od => od.Product)
                .WithMany(p => p.OrderDetails)
                .HasForeignKey(od => od.ProductId);
        }
    }

}

c# entity-framework-core dbcontext
1个回答
0
投票

您的 DbContext 有单独的项目吗?尝试指定

--project
(哪个项目包含 DbContext)和
--startup-project
(哪个项目包含连接信息)选项,如下所示:

dotnet ef migrations add MyMigration --project Foo --startup-project Bar

© www.soinside.com 2019 - 2024. All rights reserved.