Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure Entity Framework to allow database-generate uuid for PostgreSQL (npgsql)?

I'm updating our dotnet core project to use PostgreSQL on the backend instead of Microsoft SQL Server and hit a situation with two tables that use a GUID as the data type.

ERROR

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Property CommentID on type is a database-generated uuid, which requires the PostgreSQL uuid-ossp extension. Add .HasPostgresExtension("uuid-ossp") to your context's OnModelCreating.

After a little googling I then realized I have to enable the uuid extension (not sure if this can be automated somehow) and then generated a uuid in pgAdmin successfully.

CREATE EXTENSION "uuid-ossp";
SELECT uuid_generate_v4();

Unfortunately my dotnet project is still complaining with the same error tho. I see in the error it says to add .HasPostgresExtension("uuid-ossp") to OnModelCreating and I've tried in several spots but can't seem to figure out where specifically it should be added.

like image 707
chris Avatar asked Jun 01 '16 20:06

chris


People also ask

Can Postgres generate UUID?

Unfortunately, while PostgreSQL is great for storing and comparing UUID data, it lacks capabilities for creating UUID values in its core. Instead, it relies on third-party modules to create UUIDs using specified techniques.

Can I use Entity Framework with PostgreSQL?

To use the Npgsql EF Core provider, add a dependency on Npgsql. EntityFrameworkCore. PostgreSQL . You can follow the instructions in the general EF Core Getting Started docs.

What is the data type for UUID in PostgreSQL?

The data type uuid stores Universally Unique Identifiers (UUID) as defined by RFC 4122, ISO/IEC 9834-8:2005, and related standards. (Some systems refer to this data type as a globally unique identifier, or GUID, instead.)


1 Answers

As per Shay's instruction - After updating to the latest version of Npgsql, the uuid extension error is now gone. Here's a snippet of what the OnModelCreating looks like for others trying this out:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.HasPostgresExtension("uuid-ossp");
    }
like image 107
chris Avatar answered Oct 02 '22 14:10

chris