Npgsql 8.0, Entity Framework Core and JSON POCOs

Npgsql 8.0 introduced NativeAOT and trimming support (hooray!), which necessitated explicit opt-ins to some dynamic coding practices that are incompatible with NativeAOT/trimming. One of these is JSON POCO mapping which I use quite heavily in some of my projects (boo! hiss!)

As mentioned, though, it is opt-in via NpgsqlDataSourceBuilder introduced in Npgsql 7.0 or the deprecated (and not recommended) NpgsqlConnection.GlobalTypeMapper. The official documentation didn’t provide an example for Entity Framework Core, which is a tad annoying, so in the interest of lazy future me, I’m recording the code needed to enable dynamic JSON.

var dataSourceBuilder = new NpgsqlDataSourceBuilder(
    configuration.GetConnectionString("MyConnectionString")
);
dataSourceBuilder.EnableDynamicJson();
var dataSource = dataSourceBuilder.Build();
services.AddDbContext<MyDbContext>(options => options.UseNpgsql(dataSource));

That’s it.


Posted

in

by

Tags:

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.