- Auto create Context by Visual Studio. (Connected Services -> Add -> PostgreSQL)
- Install NuGet package : Microsoft.EntityFrameworkCore
- Install NuGet package : Npgsql.EntityFrameworkCore.PostgreSQL
- Add code :
builder.Services.AddDbContext<LocationAppContext>(options =>
options.UseNpgsql(System.Environment.GetEnvironmentVariable("POSTGRESQL_STRING") ?? throw new InvalidOperationException("Connection string 'LocationAppContext' not found."),
options => options.EnableRetryOnFailure().SetPostgresVersion(new Version(9, 6))
));
- Add [Key] notation for Id props
- Set Postgres version to 9.6 (to prevent GENERATED error)
- Sample Context.cs below (if required)
using LocationApp.Models;
namespace LocationApp.Data
{
public class LocationAppContext : DbContext
{
public LocationAppContext (DbContextOptions<LocationAppContext> options)
: base(options)
{
}
public DbSet<LocationApp.Models.LocationData> LocationData { get; set; } = default!;
}
}
- Install : dotnet tool install --global dotnet-ef
- Create migration : dotnet ef migrations add Mig
- Update Database : dotnet ef database update