npgsql / efcore.pg

Entity Framework Core provider for PostgreSQL

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Group by entity with xmin/xid concurrency token throws

LipatovAlexander opened this issue · comments

Possible duplicate of #2865 with additional context.

Error: Npgsql.PostgresException: 42883: could not identify an ordering operator for type xid

Repro

public class Foo
{
	public int Id { get; set; }
	
	[Timestamp]
	public byte[] Version { get; set; } = null!;
}

public class Bar
{
	public int Id { get; set; }

	public Foo Foo { get; set; } = null!;
}

public class AppDbContext : DbContext
{
	public DbSet<Foo> Foos => Set<Foo>();
	public DbSet<Bar> Bars => Set<Bar>();
	
	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		optionsBuilder.UseNpgsql();
	}

	protected override void OnModelCreating(ModelBuilder modelBuilder)
	{
		modelBuilder
			.Entity<Foo>()
			.Property(x => x.Version)
			.HasConversion(bytes => BitConverter.ToUInt32(bytes), value => BitConverter.GetBytes(value));
	}
}

using var context = new AppDbContext();

var result = context.Bars.GroupBy(x => x.Foo).ToList();

Console.WriteLine(result.Count);

We have big codebase that works in SQL Server and want to migrate it to Postgres. Code above works in SQL Server, but doesn't work in Postgres (NpgSql). While we could somehow rewrite such queries, this looks like a valid use case to us (group dependent entities by their parents).

I have tried to add custom ordering operators and default operator class for xid type. Although this solves the problem, I'm not sure this won't break something (Docs says an erroneous operator class definition could confuse or even crash the server). UPD: The Postgres team advises not to do this.

Question: How to properly use EF with concurrency tokens in case of GroupBy in Postgres?