.net EF核心dotnet ef创建迁移失败

ghhkc1vu  于 2023-01-06  发布在  .NET
关注(0)|答案(1)|浏览(177)

有以下背景:

using Microsoft.EntityFrameworkCore;

namespace InternetShop.DAL
{
    public sealed class InternetShopDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<ProductAdditInfo> ProductAdditInfos { get; set; }
        public DbSet<Characteristics> ProductsCharacteristics { get; set; }
        public DbSet<Category> Categories { get; set; }
        public InternetShopDbContext(DbContextOptions<InternetShopDbContext> options) : base(options)
        {
            Database.EnsureCreated();
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
}

我正在尝试创建迁移,但收到以下错误

Build started...
Build succeeded.
Unable to create an object of type 'InternetShopDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

更新:在我的API项目ConfigureServices的Startup.cs中,有以下代码

services.AddDbContext<InternetShopDbContext>(opt =>
    {
        opt.UseNpgsql(Configuration.GetSection("ConnectionStrings")["PostgreSql"]);
    });

我添加了--verbose标志并得到了以下异常

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[InternetShop.DAL.InternetShopDbContext]' while attempting to activate 'InternetShop.DAL.InternetShopDbConte
xt'.

有什么问题吗?

2izufjch

2izufjch1#

phuzi向我指出了一个错误。如果你有单独的ASP.NET和DAL项目,命令应该是这样的(对我来说是这样的):

dotnet ef migrations add migrationname --startup-project ..\InternetShop.Api\InternetShop.Api.csproj

启动项目中还必须安装Microsoft.EntityFrameworkCore.Design包

相关问题