Guilherme Bley
Guilherme Bley

Reputation: 376

Failed to auto generate ID in EF Core with MySql 5.6

I'm having issues with ID auto-generation with EF CORE and Mysql 5.6.

That's my Model Creating:

builder.Entity<Application.Model.FileStreamModel>(b =>
{
    b.ToTable("FilesStream");

    b.HasKey(p => p.Id);

    b.Property(p => p.Id)
      .ValueGeneratedOnAdd();

}

but the output command generated by the pomelo is:

[Parameters=[@p0='08dd34a5-af3d-4998-8fc2-b26cfaad6910', @p1='2025-01-14T14:13:54.0376360Z' (DbType = DateTime), @p2='xxx' (Nullable = false) (Size = 50), @p3='xxx' (Nullable = false) (Size = 50), @p4='2025-01-14T14:13:54.0376361Z' (DbType = DateTime), @p5='xxx' (Nullable = false) (Size = 500)], CommandType='Text', CommandTimeout='600']
      SET AUTOCOMMIT = 1;
      INSERT INTO `FilesStream` (`Id`, `InsertedAt`, `Key`, `PartialKey`, `UpdatedAt`, `Url`)
      VALUES (@p0, @p1, @p2, @p3, @p4, @p5);

Look, the DB command is not using something like 'UUID'...

Does anyone have an idea what I should do?

(OBS. I'm setting in the model an empty GUID)

Upvotes: 0

Views: 38

Answers (1)

Steve Py
Steve Py

Reputation: 34783

ValueGeneratedOnAdd's behaviour is provider dependent. For SQL Server the provider apparently uses code to generate a sequential UUID, but Pomello does not. Instead you can configure it with a server-side default: .HasDefaultValueSql("(uuid())") https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues/835

UUID generation for index performance (fragmentation) is database specific based on factors liked Endian-ness so it isn't a one-size-fits-all scenario.

Alternatively you can look at finding/writing a C# Guid formatter suitable for transforming the byte order into something suited to MySQL. I had to do something similar coming into a project for SQL Server and EF6 where they had relied on client-side Guid.New() everywhere, which involved a search and replace to Guid.NewSequential() using an extension method with the suited translation.

Upvotes: 0

Related Questions