DEV Community

Ignacy Starczynski
Ignacy Starczynski

Posted on

Entity Framework Core model definition in C#

🍂 This model configuration is used to map C# objects to the database structure.

Image description

Here's what this piece of code does ✨

  1. modelBuilder.Entity<WorkItem>(eb => { ... }); - Creates a configuration for an entity named WorkItem within the data model context. All the properties and relationships of this model are defined within this block.

  2. eb.Property(wi => wi.State).IsRequired(); - Specifies that the State property is required (NOT NULL) in the database.

  3. eb.Property(wi => wi.Area).HasColumnType("varchar200"); - Specifies the column type of the Area property as varchar(200).

  4. eb.Property(wi => wi.IterationPath).HasColumnName("Iteration_Path"); - Sets the column name in the database to "Iteration_Path" for the IterationPath property.

  5. eb.Property(wi => wi.Efford).HasColumnType("decimal(5,2)"); - Specifies the column type of the Efford property as decimal(5,2).

  6. eb.Property(wi => wi.EndDate).HasPrecision(3); - Sets the precision of the EndDate column to 3 decimal places.

  7. eb.Property(wi => wi.Activity).HasMaxLength(100); - Specifies a maximum length of 100 characters for the Activity column.

  8. eb.Property(wi => wi.RemainingWork).HasPrecision(13,3); - Specifies a precision of 13 total digits and 3 decimal places for the RemainingWork column.

  9. eb.HasMany(w => w.comments) ... - Defines a "one-to-many" relationship between the WorkItem entity and the Comment entity.

  10. eb.HasOne(w => w.Author) ... - Defines a "one-to-many" relationship between the WorkItem entity and the Author entity.

  11. eb.HasMany(w => w.Tags) ... - Defines a "many-to-many" relationship between the WorkItem entity and the Tag entity through the auxiliary entity WorkItemTag. The UsingEntity method is used to customize the mapping of the many-to-many relationship.

The final UsingEntity block configures the intermediary entity WorkItemTag, which allows customization of the mapping of the many-to-many relationship. It also sets a default value for the PublicationDate column using HasDefaultValueSql("getutcdate()").


This code is an example of model configuration in Entity Framework Core and defines how entities and their relationships will be mapped to a database.

Top comments (0)