SQL Server Data Type Mappings (EF 與 SQL 型別對照)
2022-02-09
筆記 SQL Server 各種 DataType 如何對應到 .Net 的類別,使用時機如設計資料庫綱要與使用 EntityFramework Database First 評估從 Database Table 到 Model Class,或者是反向以 Code First 從 Model Class 到 Database Table。
對照
Frequently Used
| SQL Server Database Engine type | .NET Framework type |
|---|---|
| bit | Boolean |
| datetime | DateTime |
| datetime2 | DateTime |
| decimal | Decimal |
| float | Double |
| int | Int32 |
| char | String / Char[] |
| varchar | String / Char[] |
| nchar | String / Char[] |
| nvarchar | String / Char[] |
Unexpected
| SQL Server Database Engine type | .NET Framework type |
|---|---|
| binary | Byte[] |
| image | Byte[] |
| money | Decimal |
| tinyint | Byte |
| real | Single |
Full Mappings
從 SQL Server DataType 到 .NET Framework 除字串類型相容 String 以及 Char[] 都情況外,都是一對一的轉換;但如果是從 .NET Framework Type 要轉換成 SQL Server DataType 就是多對一的情況,沒有辦法直接轉換。這個問題對於 Code First 來說應該有另外的處理方法?
| SQL Server Database Engine type | .NET Framework type |
|---|---|
| bigint | Int64 |
| binary | Byte[] |
| bit | Boolean |
| char | String / Char[] |
| date new | DateTime |
| datetime | DateTime |
| datetime2 new | DateTime |
| datetimeoffset new | DateTimeOffset |
| decimal | Decimal |
| FILESTREAM (varbinary(max)) | Byte[] |
| float | Double |
| image | Byte[] |
| int | Int32 |
| money | Decimal |
| nchar | String / Char[] |
| ntext | String / Char[] |
| numeric | Decimal |
| nvarchar | String / Char[] |
| real | Single |
| rowversion | Byte[] |
| smalldatetime | DateTime |
| smallint | Int16 |
| smallmoney | Decimal |
| sql_variant | Object |
| text | String / Char[] |
| time new | TimeSpan |
| timestamp | Byte[] |
| tinyint | Byte |
| uniqueidentifier | Guid |
| varbinary | Byte[] |
| varchar | String / Char[] |
| xml | Xml |
說明
- new
- SQL Server 2008 後出現的 Data Type