The Fluent API HasColumnType Method

The HasColumnType method is applied to a property to specify the data type of the column that the property should map to when the type differs from convention. The following example specifies that the Title column in the Books table is to be configured as varchar instead of the default nvarchar:

public class SampleContext : DbContext
{
    public DbSet<Book> Books { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Book>()
            .Property(b => b.Title).HasColumnType("varchar");
    }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
}

The HasColumnType method is also useful when mapping columns to user defined data types. In the next example, the StateProvince property on the Address entity is mapped to the "Name" user defined data type:

public class SampleContext : DbContext
{
    public DbSet<Address> Address { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Address>()
            .Property(a => a.StateProvince).HasColumnType("Name");
    }
}

This example is taken from the AdventureWorks sample database for SQL server provided by Microsoft.

Data Annotations

The data annotations approach to specifying the data type of the mapped column is to provide a value for the TypeName property of the Column attribute.


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