當前位置:
首頁 >
初探EntityFramework——实体类结构映射
發布時間:2025/3/11
31
豆豆
生活随笔
收集整理的這篇文章主要介紹了
初探EntityFramework——实体类结构映射
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實體類與數據表的映射有一套專用的規則。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 | ? |
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的初探EntityFramework——实体类结构映射的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何用c语言从txt文件中读取数据
- 下一篇: gradle下bug修正后问题仍存在解决