postgresql 无法创建类型为的对象

kqhtkvqz  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(188)

当我尝试使用这个命令dotnet ef migrations add InitialCreate时,
我得到的错误像:Unable to create an object of type 'BlogDbContext'. For the different patterns supported at design time etc...
我也尝试了这个(dotnet tool install --global dotnet-ef)解决方案,但不适合我。
我的BlogDbContext代码:

public class BlogDbContext : DbContext
{
    public BlogDbContext(DbContextOptions<BlogDbContext> options) : base (options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Blog>();
    }
}

字符串
我还添加了我的App类。App类包含了我的Run函数。

public class App
{
    public App()
    {
    }

    public void Run()
    {
        var services = new ServiceCollection();
        var connstr = "Host=localhost;Database=blog;Port=5432;Username=postgres;Password=mysecretpassword";
        services.AddDbContext<BlogDbContext>(x => x.UseNpgsql(connstr).UseSnakeCaseNamingConvention());
        var provider = services.BuildServiceProvider();

        using (var ctx = provider.GetService<BlogDbContext>())
        {
            ctx.Add(new Blog());
            ctx.SaveChanges();
        }
    }
}

vqlkdk9b

vqlkdk9b1#

添加一个构造函数到您的BlogDbContext,它将修复这个问题。我发现了这个问题,并在Microsoft文档站点添加反馈。

public class BlogDbContext : DbContext
{
    // add this method
    public BlogDbContext()
    {
    }
    public BlogDbContext(DbContextOptions<BlogDbContext> options) : base (options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Blog>();
    }
}

字符串

ioekq8ef

ioekq8ef2#

在Jason Pan的回答帮助下,我解决了以下问题

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext() { }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // I had to add this if statement
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder
                .UseNpgsql(configuration.GetConnectionString("DefaultConnection"));
        }
    }

    public DbSet<YourModel> Models { get; set; }
}

字符串

相关问题