Search code examples
c#postgresql.net-coreentity-framework-corenpgsql

Create new database using Entity Framework Core, npgsql, PostgreSQL


Newb here sorry. I'm reading up Entity Framework Core, npgsql and PostgreSQL (new to all of these things!!) Can someone please very kindly explain or point me where to read: I am trying to create a brand new database using code.

From the things I have read, I am creating the DB using pgadmin or script directly. What I want to do is create a database all via code (so the user can install Postgresql and my website but not have to worry about any direct SQL commands with PostgreSQL).

Thank you!


Solution

  • There are two ways to have EF Core create the database:

    1. Use the lightweight EnsureCreated() method, which simply creates your database base on the model. If you're just starting out, it's probably best to start here, see the docs.
    2. Use migrations, which also take care of updating your database schema as your code model changes. For example, if you add a property to one of your C# classes, EF Core can automatically generate a migration that will add the corresponding column to the table. Here are the docs for that.

    The general docs for this are here. As a general rule, read and understand the EF Core docs first, then you can look at database- and provider-specific details (e.g. PostgreSQL/Npgsql).