警告

This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef. 本文档是基于EF7版本.对于EF6.x及更早的版本请参见 http://msdn.com/data/ef.

注解

This article uses EF 7.0.0-rc1 which is the latest pre-release available on NuGet.org. You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/ but we do not maintain up-to-date documentation for nightly builds.

注解

The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared EntityFramework.Relational package).

Data Types

Data type refers to the database specific type of the column to which a property is mapped.

In this article:

Conventions

By convention, the database provider selects a data type based on the CLR type of the property. 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 uses datetime2(7) for DateTime properties, and nvarchar(max) for string properties (or nvarchar(450) for string properties that are used as a key).

Data Annotations

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

1
2
3
4
5
6
    public class Blog
    {
        public int BlogId { get; set; }
        [Column(TypeName = "varchar(200)")]
        public string Url { get; set; }
    }

Fluent API

You can use the Fluent API to specify an exact data type for the column.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    class MyContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }

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

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }

If you are targeting more than one relational provider with the same model then you probably want to specify a data type for each provider rather than a global one to be used for all relational providers.

1
2
3
            modelBuilder.Entity<Blog>()
                .Property(b => b.Url)
                .ForSqlServerHasColumnType("varchar(200)");