Skip to content

[Bug?] Why is UniqueConstraintException.ConstraintProperties collection null for alternate key? #87

@voroninp

Description

@voroninp

I'm witnessing a weird behavior.

If I try to insert an entity with the same PK, I get Common.UniqueConstraintException with ContratintProperties: ["Id"].
If I declare a nuique index on property and try to insert an entity with the duplicate value, I get Common.UniqueConstraintException with ContratintProperties: ["Property"].
However, if I declare an alternative key instead of the index, I get Common.UniqueConstraintException with ContratintProperties: null.

Code to reproduce:

using EntityFramework.Exceptions.PostgreSQL;
using Microsoft.EntityFrameworkCore;
using Testcontainers.PostgreSql;

var container = new PostgreSqlBuilder().WithDatabase("app-db").WithPortBinding(5555, 5432).Build();
await container.StartAsync();

var ctx = new AppDbContext(container.GetConnectionString());
await ctx.Database.EnsureCreatedAsync();
var e = new Entity { Property = 1 };
await ctx.AddAsync(e);
await ctx.SaveChangesAsync();
ctx.Entry(e).State = EntityState.Detached;

e = new Entity { Property = 1 };
await ctx.AddAsync(e);
await ctx.SaveChangesAsync();

Console.ReadKey();

public sealed class AppDbContext(string connectionString) : DbContext()
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseExceptionProcessor()
            .EnableSensitiveDataLogging()
            .UseNpgsql(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Entity>(b =>
        {
            //b.HasIndex(p => p.Property).IsUnique();
            b.HasAlternateKey(p => p.Property);
        });
    }
}

public sealed class Entity
{
    public int Id { get;  set; }

    public int Property { get; set; }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions