Skip to main content
Neon Postgres Docs
current

Search documentation

Type to search this documentation.

On this pageOverview

Connect an Entity Framework application to Neon

This guide describes how to create a Neon project and connect to it from an Entity Framework Core application. The example demonstrates how to set up a basic ASP.NET Core Web API project with Entity F...

Pre-built prompt for connecting .NET Entity Framework projects to Lakebase Postgres.

This guide describes how to create a Neon project and connect to it from an Entity Framework Core application. The example demonstrates how to set up a basic ASP.NET Core Web API project with Entity Framework Core using Npgsql as the database provider.

To connect to Neon from an Entity Framework application:

  1. Create a Neon Project
  2. Create a .NET project and add dependencies
  3. Configure Entity Framework
  4. Run the application

If you do not have one already, create a Neon project.

  1. Navigate to the Projects page in the Neon Console.
  2. Click New Project.
  3. Specify your project settings and click Create Project.
  1. Create a new ASP.NET Core Web API project and change to the newly created directory:

    Bash
    dotnet new webapi -n NeonEfExample
    cd NeonEfExample
  2. Delete the files WeatherForecast.cs and Controllers/WeatherForecastController.cs as we won't be using them:

    Bash
    rm WeatherForecast.cs Controllers/WeatherForecastController.cs
  3. Install required packages

    Bash
    dotnet tool install --global dotnet-ef --version YOUR_DOTNET_VERSION
    dotnet add package Microsoft.EntityFrameworkCore.Design --version YOUR_DOTNET_VERSION
    dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version YOUR_DOTNET_VERSION
  1. Create a model class in Models/Todo.cs:

    C#
    namespace NeonEfExample.Models
    {
        public class Todo
        {
            public int Id { get; set; }
            public string? Title { get; set; }
            public bool IsComplete { get; set; }
        }
    }
  2. Create a database context in Data/ApplicationDbContext.cs:

    C#
    using Microsoft.EntityFrameworkCore;
    using NeonEfExample.Models;
    
    namespace NeonEfExample.Data
    {
        public class ApplicationDbContext : DbContext
        {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                : base(options)
            {
            }
    
            public DbSet<Todo> Todos => Set<Todo>();
        }
    }
  3. Update appsettings.json / appsettings.Development.json:

    Add the connection string:

    JSON
    {
      "ConnectionStrings": {
        "TodoDbConnection": "Host=your-neon-host;Database=your-db;Username=your-username;Password=your-password;SSL Mode=Require"
      }
    }
  4. Create a Todo controller in Controllers/TodoController.cs:

    C#
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using NeonEfExample.Data;
    using NeonEfExample.Models;
    
    namespace NeonEfExample.Controllers
    {
        [ApiController]
        [Route("api/[controller]")]
        public class TodoController : ControllerBase
        {
            private readonly ApplicationDbContext _context;
    
            public TodoController(ApplicationDbContext context)
            {
                _context = context;
            }
    
            [HttpGet]
            public async Task<ActionResult<IEnumerable<Todo>>> GetTodos()
            {
                return await _context.Todos.ToListAsync();
            }
    
            [HttpPost]
            public async Task<ActionResult<Todo>> PostTodo(Todo todo)
            {
                _context.Todos.Add(todo);
                await _context.SaveChangesAsync();
                return CreatedAtAction(nameof(GetTodos), new { id = todo.Id }, todo);
            }
        }
    }
  5. Update Program.cs:

    C#
    using Microsoft.EntityFrameworkCore;
    using NeonEfExample.Data;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddControllers();
    
    builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
    
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    var app = builder.Build();
    
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseAuthorization();
    app.MapControllers();
    
    if (app.Environment.IsDevelopment())
    {
        app.Run("http://localhost:5001");
    }
    else
    {
        app.UseHttpsRedirection();
        app.Run();
    }
  6. Create and apply the initial migration:

    Bash
    dotnet ef migrations add InitialCreate
    dotnet ef database update
  1. Start the application:

    Bash
    dotnet run
  2. Test the connection by navigating to http://localhost:5001/swagger in your browser. You can use the Swagger UI to create and retrieve Todo items.

Join our Discord Server to ask questions or see what others are doing with Neon. For paid plan support options, see Support.

Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu