Data Types

Tipi di dato nei database: come avviene il mapping dei tipi del C# in tipi del database sottostante

Overview

When using a relational database, the database provider selects a data type based on the .NET type of the property1. It also takes into account other metadata, such as the configured maximum length, whether the property is part of a primary key, etc. For example, SQL Server maps DateTime properties to datetime2(7) columns, and string properties to nvarchar(max) columns (or to nvarchar(450) for properties that are used as a key). You can also configure your columns to specify an exact data type for a column.

You can use Data Annotations to specify an exact data type for a column.

 1public class Blog
 2{
 3    public int BlogId { get; set; }
 4
 5    [Column(TypeName = "varchar(200)")] //👈 data annotation
 6    public string? Url { get; set; }
 7
 8    [Column(TypeName = "decimal(5, 2)")] //👈 data annotation
 9    public decimal Rating { get; set; }
10}

You can also use the Fluent API to specify the same data types for the columns.

 1class MyContext : DbContext
 2{
 3    public DbSet<Blog> Blogs { get; set; }
 4
 5    protected override void OnModelCreating(ModelBuilder modelBuilder)
 6    {
 7        modelBuilder.Entity<Blog>(eb =>
 8        {
 9            eb.Property(b => b.Url).HasColumnType("varchar(200)");//👈 Fluent API
10            eb.Property(b => b.Rating).HasColumnType("decimal(5, 2)");//👈 Fluent API
11        });
12    }
13}
14
15public class Blog
16{
17    public int BlogId { get; set; }
18    public string? Url { get; set; }
19    public decimal Rating { get; set; }
20}