1
votes

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!

1
You just need to add an initial migration - is this not covered here? docs.microsoft.com/en-us/ef/core/managing-schemas/migrationsGPW
Thanks for confirming that, I wasn't sure if it was that simple! But how does it know what the name of the database is that I want to create? Is it because I specify it in the connection string?PKCS12
yes. plus of course the specified user needs to have create database rights. I think the usual recommendation is to still use scripts though - you can use the Script-Migration command to generate these for you. This lets you have more control over upgrades to existing dbs later (e.g. copying data into a new table before dropping a column). I use a version-controlled DB Create script for an EF Core project I have which I generate this way and it works well so far.GPW
Many thanks for the useful info. Appreciate it a lot.PKCS12

1 Answers

4
votes

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).