Monday, January 20, 2025

EF Core 9.0: Reading EntityConfigurations from Classes with Non-Public Constructors

In this post let's have a look at another feature in EF Core 9.0.

Consider the following code example.
public record Employee
{
    public int Id { getset}

    public string Name { getset}

    private class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
    {
        private EmployeeConfiguration() { }

        public void Configure(EntityTypeBuilder<Employee> builder)
        {
            builder.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(50);
        }
    }
}
Prior to EF Core 9.0, if you try to ApplyConfigurationsFromAssembly, above EmployeeConfiguration will not be discovered. Because the entity configurations had to be types with a public, parameterless constructor.

But with EF Core 9.0, above EmployeeConfiguration will be discovered and we don't need to have a have a public type anymore.

While maintaining Entity Configuration along with Entity seem polluting the domain, I can certainly see an advantage. We now no longer have to look at a different file to see a particular entities configurations, everything is in one place. 

At least now we don't have a code constraint, the developer can decide which approach (public type vs private type) they are going to take.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment