Search code examples
entity-framework-corenpgsql

How to add complex unique index/constraint with a private field?


In the example below, MyModel class has a private nullable backing field for the name: _name. Is there any way to create a unique index including it without exposing it to external classes?

I cannot find any solutions but I presume there must be a way since EF Core can populate a model with a private parameterless constructor.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ASPNetCoreEmpty.Models;

public class MyModel
{
    public int Id { get; set; }
    public required RelatedModel RelatedModel { get; set; }
    private string? _name;
    public string Name => _name ?? RelatedModel.Name;
}

public class MyModelConfiguration : IEntityTypeConfiguration<MyModel>
{
    public void Configure(EntityTypeBuilder<MyModel> builder)
    {
        builder.HasIndex(x => new { x.RelatedModel, x._name }) // How to include private property here?
            .IsUnique();
    }
}

public class RelatedModel
{
    public int Id { get; set; }
    public required string Name { get; set; }
}

Solution

  • As with all EF model configuration APIs, you can use the string-based overload:

    builder.HasIndex(new[] { "RelatedModel", "_name" }).IsUnique();