Batch update with non comparable primary key fails
When updating a batch of entities who have a non comparable id. The following exception is thrown.
Is it mandatory for a primary key to be comparable?
Failed to compare two elements in the array.
at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.<BatchCommands>d__14.MoveNext()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded) in C:\projects\npgsql-entityframeworkcore-postgresql\src\EFCore.PG\Storage\Internal\NpgsqlExecutionStrategy.cs:line 39
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at NonComparablePrimaryKey.Program.Main(String[] args) in C:\projects\NonComparablePrimaryKey\NonComparablePrimaryKey\Program.cs:line 36
When searching in the code the following chunk of code is causing the issue.
https://github.com/aspnet/EntityFrameworkCore/blob/aca49588a691c3b617502dcd8d67e5eb4b284558/src/EFCore.Relational/Update/Internal/ModificationCommandComparer.cs#L101-L111
Steps to reproduce
public class Program
{
static void Main(string[] args)
{
// Seed database
using (var db = new Context())
{
for (int i = 0; i < 100; i++)
{
db.MyEntitySet.Add(new MyEntity(new MyEntityId(i))
{
StringValue = "",
});
}
db.SaveChanges();
}
// Update entities
using (var db = new Context())
{
foreach (var entity in db.MyEntitySet)
{
entity.StringValue = "foo";
}
db.SaveChanges();
}
}
}
public class MyEntityId : IEquatable<MyEntityId>
{
public MyEntityId(int value)
{
this.Value = value;
}
public int Value { get; }
public override bool Equals(object obj)
{
return base.Equals(obj as MyEntityId);
}
public bool Equals(MyEntityId other)
{
return ReferenceEquals(other, this) || (
!ReferenceEquals(other, null) &&
this.Value == other.Value);
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
}
public class MyEntity
{
public MyEntity(MyEntityId myEntityId)
{
this.Id = myEntityId;
}
private MyEntity()
{
}
public MyEntityId Id { get; private set; }
public string StringValue { get; set; }
}
public class Context : DbContext
{
public DbSet<MyEntity> MyEntitySet { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseNpgsql(@"Host = 127.0.0.1; Port = 5432; Database = test; Username = postgres; Password = postgres;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Converters
var myEntityIdConverter = new ValueConverter<MyEntityId, int>(
id => id.Value,
id => new MyEntityId(id),
new ConverterMappingHints(valueGeneratorFactory: (p, t) => new MyEntityIdValueGenerator()));
modelBuilder.Entity<MyEntity>(myEntity =>
{
// Columns
myEntity.HasKey(p => p.Id);
myEntity.Property(p => p.Id)
.HasConversion(myEntityIdConverter)
.ValueGeneratedOnAdd();
});
}
private sealed class MyEntityIdValueGenerator : ValueGenerator<MyEntityId>
{
private int current = int.MinValue + 1000;
public override bool GeneratesTemporaryValues => true;
public override MyEntityId Next(EntityEntry entry)
{
var id = Interlocked.Increment(ref this.current);
return new MyEntityId(id);
}
}
Further technical details
EF.Core version: 2.2.6 Database Provider: Npgsql.EntityFrameworkCore.PostgreSQL Operating system: Windows 10 1803 Visual Studio 2019 16.2.2
Is it mandatory for a primary key to be comparable?
@KarelCoudijzer Yes, MyEntityId should implement IComparable<MyEntityId>
@AndriySvyryd Could you explain why this is mandatory? As I understand a primary key must be unique, so implementing IEquatable<MyEntityId> should be sufficient.
I also think order has no meaning on an MyEntityId or do I miss something?
@KarelCoudijzer We need a deterministic order when updating rows because if there are two threads updating the same rows and the order is reversed it might result in a deadlock (see https://github.com/aspnet/EntityFrameworkCore/issues/6666)
Note from triage: closing as by-design since we need a stable ordering for updates.