New SberryHello! Strawberry Sberry here. This time strawberry in search of a new tech friend. Sberry came to know about EntityTypeConfiguration from its previous tech friend DbContext. Let’s help Sberry discover about its new friend and connect them.

Go Go Goooo……..

EntityTypeConfiguration is a most important class to configure the entities. It can be accessed by the ModelBuilder class’s Entity() method. EntityTypeConfiguration has 12 methods notably

  1. GetType()
  2. HasEntitySetName()
  3. HasKey()
  4. HasMany()
  5. HasOptional()
  6. HasRequired()
  7. ToTable()
  8. Map()
  9. MapToStoreProcedures()
  10. Ignore()
  11. HasTableAnnotations()
  12. Property()

Map and Property methods have generic versions.

A Quick Look at how to obtain EntityTypeConfiguration object and use the methods
protected override void OnModelCreating(DbModelBuilder modelBuilder)
m.Properties(t => new { t.Id, t.Name });

The code above creates a table named StudentMain in the database with Id and Name Columns.

Similarly, the Property method of EntityTypeConfiguration is used to configure the selected entity attributes. Property() returns a configuration object for a given property(Id in our example) which can be specified as a lambda expression, Action Delegate.
.Property(s=> s.Id)

The options on the configuration object are specific to the type being configured; IsUnicode is available only on string properties for example.The following options are available for property configuration depending on the type.

  1. GetType
  2. HasColumnAnnotation()
  3. HasColumnName()
  4. HasParameterName()
  5. HasColumnType()
  6. HasColumnOrder()
  7. IsRequired()
  8. HasMaxLength()
  9. IsMaxLength()
  10. IsFixedLength()
  11. IsVariableLength()
  12. HasDatabaseGeneratedOption()
  13. IsOptional()
  14. IsUnicode()
  15. IsConcurrencyToken()
  16. MapInheritedProperties()
  17. MapKey()
  18. MapLeftKey()
  19. MapRightKey()

I want to highlight some of my favorite configurations where there are  potential for getting struck into the pit.

Configuring a composite primary key

Renaming the foreign key

We can make a CLR type not to be mapped to a table in the database using the ignore method like

In the same lines, we can prevent a CLR property from being mapped to any column in a table as

Yeah! Viola Sberry is happy to know about EnityTypeConfiguration. They got into a deep friendship. Bye Bye.Let’s be back with Sberry again.