skip to Main Content

I can’t figure out where i made a mistake.

I have 2 schemas in my db (Postgre): BooksStore and PollHub.
My project should use BooksStore. I use ef code-first method to create tables in schema.

So I google for two days and trying every possible solutions but nothing really work.

Here some fragments from my code:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.HasDefaultSchema("booksstore");
    builder.Entity<BookEntity>().ToTable("Books", schema: "BooksStore");

    base.OnModelCreating(builder);
}

My connection string: "Host=;Port=5432;Database=postgres;SearchPath=BooksStore;Username=postgres;Password=;"
I tried without searchpath – all the same.

I can provide more code fragments or something else if it necessary.

I granted usage and create for my schema to public and postgres role (but I guess it has usage and create by default as owner).

Does someone know what sould I try next. Is there a problem with my db configuration?

2

Answers


  1. If Schema already exists you can write below and table will create
    make sure schema name should exact same as you created and also check case

    public BooksContext(DbContextOptions<BooksContext> options) : base(options) { }
    
    public DbSet<Book> Books { get; set; }
    
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.HasDefaultSchema("BooksStore");
    }
    
    Login or Signup to reply.
    1. Is code-first correct? "I have 2 schemas in my db (Postgre): BooksStore and PollHub. My project should use BooksStore. I use ef code-first method to create tables in schema." If you have something in the database, is code-first the correct choice?

    2. Your context should look like in the answer by @Harshini if code-first is correct choice.

    public BooksContext(DbContextOptions<BooksContext> options) : base(options) { }
    
    public DbSet<Book> Books { get; set; }
    
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.HasDefaultSchema("BooksStore");
    }
    
    1. Make sure that you have created the migration. Without migrations, no changes to database will be done About EF Core Migrations. Also, it seems like you may have more than one DbContext, in this case you will need to provide, which context to run Migrations with multiple DbContext

    2. You need to apply pending migrations either using terminal or in code. My preferred method is to run them on app startup. Something like this assuming it’s a web app:

    using (var scope = app.Services.CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<BooksContext>();
        context.Database.migrate();
    }
    

    Hope this helps 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search