实体类与数据表的映射有一套专用的规则。Code First 采用的惯例优于预先设置的设计,在没有任何设置的情况下,自动检测模型结构并推导出默认设置以简化类的设计,因此不需要特别设置类的属性即可完成模型设计。
例如,当DbContext的模型类中定义了DbSet<Product>属性时, 按照惯例会以复数类名称为映射的数据表名称,因为Product自动映射到Products数据表。
而Product中的属性则逐一映射到Products数据表中的同名数据字段,比如Product类如下所示:
public class Product
{public int Id {get;set;}public string Name {get;set;}public int Price {get;set;}public string Category {get;set;}
}
其中名称为Id的属性(不区分大小写,Id与ID效果相同)自动成为主键,类名+Id的属性 名称同样会被推断为主键,例如ProductId
EntityFramework同样会在映射过程中自动推导出类属性与数据字段的映射类型,如下图所示:
| SQL Server Database Engine type | .NET Framework type |
| image,timestamp | Byte[] |
| bigint | Int64 |
| int | Int32 |
| float | Double |
| bit | Boolean |
| char,nchar,ntext,varchar,nvarchar,text | String/Char[] |
| date,datetime,datetime2 | DateTime |
| decimal,numeric,money | Decimal |
| time | TimeSpan |
| uniqueidentifier | Guid |
注意:主键属性映射字段不允许为Null,基本类型(比如int 类型)属性映射的字段也不允许是Null,其他类型属性(比如string)映射的字段均允许是Null.
Product类映射到数据库的表结构如下图所示:

更多信息,请参考微软MSDN官方说明:EF微软官方文档
后续补充
| SQL Server类型目录 | SQL Server类型 | .NET类型 | C# 关键字 |
| 准确数字型 | bit | system.Boolean | bool |
| tinyint | system.Byte | byte | |
| smallint | system.Int16 | short | |
| int | system.Int32 | int | |
| bigint | system.Int64 | long | |
| smallmoney、money、decimal、numeric | system.Decimal | decimal | |
| 近似数字类型 | real | system.Deciaml | float |
| float | system.Double | double | |
| 字符串类型 | char、varchar、text | system.String | string |
| nchar、varchar、ntext | system.String | string | |
| 二进制字符串类型 | binary、varbinary | system.Byte[] | byte[] |
| image | system.Byte[] | byte[] | |
| rowversion(timestamp) | system.Byte[] | byte[] | |
| 日期类型 | date | system.DateTime | |
| time | system.TimeSpan | ||
| small datetime、datetime、datetime2 | system.DateTime | ||
| datetimeoffest | system.DateTimeOffset | ||
| 其他类型 | hierarchyid | No built-in mapping or support | |
| xml | system.String | string | |
| uniqueidentifier | system.Guid | ||
| sql_variant | No bulit-in mapping or support |