Entity Framework Core

edit

Store IDs as their values

The generator does not write anything specific to Entity Framework Core. Write a ValueConverter between the ID and its value, with Value and the factory method, and apply it to every property of the ID type in ConfigureConventions:

public sealed class Project
{
    public ProjectId Id { get; set; }
    public required string Name { get; set; }
}

// Stores a ProjectId as its int value
public sealed class ProjectIdConverter() : ValueConverter<ProjectId, int>(id => id.Value, value => ProjectId.FromInt32(value));

public sealed class ProjectsContext(DbContextOptions<ProjectsContext> options) : DbContext(options)
{
    public DbSet<Project> Projects => Set<Project>();

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        // Applies the converter to every ProjectId property of the model
        configurationBuilder.Properties<ProjectId>().HaveConversion<ProjectIdConverter>();
    }
}

The column has the type of the value (INTEGER with SQLite for an int), and queries can compare IDs:

await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<ProjectsContext>().UseSqlite(connection).Options;

await using (var context = new ProjectsContext(options))
{
    await context.Database.EnsureCreatedAsync();
    context.Projects.Add(new Project { Id = ProjectId.FromInt32(42), Name = "Documentation" });
    await context.SaveChangesAsync();
}

await using (var context = new ProjectsContext(options))
{
    // The id in the query is converted to its value
    var project = await context.Projects.SingleAsync(p => p.Id == ProjectId.FromInt32(42));
    Assert.Equal("Documentation", project.Name);
}
  • ConfigureConventions applies the converter to every ProjectId property, keys and foreign keys included. To configure one property instead, call HasConversion<ProjectIdConverter>() on it in OnModelCreating.
  • Write one converter per ID type. Reading values from the database goes through the factory method, so a validating constructor also rejects invalid rows.
  • Entity Framework Core does not generate the values of a key that has a value converter: the key is never generated by default. Create the value in the application, for instance with New() for a Guid ID, or configure the value generation of the key.