For those looking for a more recent example, in efcore version 6 you can implement an IEntityTypeConfiguration
, and include the registration in your setup as follows;
public class MyEntityConfiguration : IEntityTypeConfiguration<MyEntity>
{
public void Configure(EntityTypeBuilder<MyEntity> builder)
{
builder.Property(o => o.MyProperty).HasMaxLength(2000);
}
}
And include the registration on your DbContext
class;
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());//Your assembly here
base.OnModelCreating(builder);
}
I personally prefer this method because you separate out the concerns into different files, rather than having a monolithic DbContext. This answer does not preclude the other answers, it's just an additional option.