Property Configuration In Entity Framework Core

Entity Framework Core provides a range of options for configuring entity properties using the Fluent API. These options are available as methods that can be chained to the EntityTypeBuilder.Property method, which is available in number of versions. Some take the name of the property to be configured as strings:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Entity>().Property(typeof(string), "PropertyName"))...
}

or

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Entity>().Property<string>("PropertyName")....
}

Most often, you will see the version that takes a lambda expression denoting the property to be configured. This option provides strong typing and therefore Intellisense assistance and is the preferred option used throughout this guide:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<EntityName>().Property(p => p.PropertyName)...
}

Methods available for property configuration are detailed below. Note that a number of additional provider-specific methods may also become available depending on the database provider that you use.

HasAnnotation Provides a means to apply annotations via the Fluent API
HasColumnName Specifies the name of the database column that the property should map to
HasColumnType Specifies the data type of the database column that the property should map to
HasDefaultValue Configures the default value of the database column that the property maps to
HasDefaultValueSql Configures the default value expression for the database column that the property maps to
HasMaxLength Specifies maximum length of data that can be stored for strings or binary data (arrays)
IsConcurrencyToken Denotes that the property takes part in concurrency management
IsRequired Configures the database column as not nullable
ValueGeneratedNever Specifies that the database should not automatically generate values for the property
ValueGeneratedOnAdd Specifies that values should only be generated automatically when new data is added
ValueGeneratedOnAddOrUpdate Specifies that values should be generated automatically when data is added or updated

Created:
Last updated: 14/03/2017 16:33:45
Proficiency Level: Beginner