Search code examples
c#jsonpostgresqlentity-framework-corenpgsql

How to set up JSON columns with Npgsql?


I'm setting up a mini model and I'm getting this exception when executing the code from the docs website.

Here's my code:

  public class SomeEntity
  {
    public int Id { get; set; }
    [Column(TypeName = "jsonb")]
    public Customer Customer { get; set; }
  }

  public class Customer    // Mapped to a JSON column in the table
  {
    public string Name { get; set; }
    public int Age { get; set; }
    public Order[] Orders { get; set; }
  }

  public class Order       // Part of the JSON column
  {
    public decimal Price { get; set; }
    public string ShippingAddress { get; set; }
  }
using (var dbContext = services.GetRequiredService<AppDbContext>())
{
  await dbContext.Database.MigrateAsync();

  dbContext.SomeEntities.Add(
    new SomeEntity
    {
      Customer = new Customer
      {
        Name = "Roji",
        Age = 35,
        Orders = new[]
        {
          new Order { Price = 3, ShippingAddress = "Somewhere" },
          new Order { Price = 3, ShippingAddress = "Nowhere" }
        }
      }
    });

  await dbContext.SaveChangesAsync();
}

When I call SaveChanges, I get the following exception:

Npgsql.PostgresException: 42P01: relation \"SomeEntities\" does not exist

Here's a repro project.

Since I believe I followed all the steps in the manual, I've opened an issue here too.


Solution

  • You're calling the MigrateAsync method, but your project doesn't have any actual migrations (those can be created with dotnet ef migrations add <name>). If you're just playing around, you likely want to call dbContext.Database.EnsureCreated instead, see this doc page.