初探EntityFramework——实体类结构映射
實(shí)體類與數(shù)據(jù)表的映射有一套專用的規(guī)則。Code First 采用的慣例優(yōu)于預(yù)先設(shè)置的設(shè)計(jì),在沒(méi)有任何設(shè)置的情況下,自動(dòng)檢測(cè)模型結(jié)構(gòu)并推導(dǎo)出默認(rèn)設(shè)置以簡(jiǎn)化類的設(shè)計(jì),因此不需要特別設(shè)置類的屬性即可完成模型設(shè)計(jì)。
例如,當(dāng)DbContext的模型類中定義了DbSet<Product>屬性時(shí),?按照慣例會(huì)以復(fù)數(shù)類名稱為映射的數(shù)據(jù)表名稱,因?yàn)?strong>Product自動(dòng)映射到Products數(shù)據(jù)表。
而Product中的屬性則逐一映射到Products數(shù)據(jù)表中的同名數(shù)據(jù)字段,比如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的屬性(不區(qū)分大小寫(xiě),Id與ID效果相同)自動(dòng)成為主鍵,類名+Id的屬性?名稱同樣會(huì)被推斷為主鍵,例如ProductId
EntityFramework同樣會(huì)在映射過(guò)程中自動(dòng)推導(dǎo)出類屬性與數(shù)據(jù)字段的映射類型,如下圖所示:
| 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類映射到數(shù)據(jù)庫(kù)的表結(jié)構(gòu)如下圖所示:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
?
?更多信息,請(qǐng)參考微軟MSDN官方說(shuō)明:EF微軟官方文檔
后續(xù)補(bǔ)充?
| SQL Server類型目錄 | SQL Server類型 | .NET類型 | C# 關(guān)鍵字 |
| 準(zhǔn)確數(shù)字型 | 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 | |
| 近似數(shù)字類型 | real | system.Deciaml | float |
| float | system.Double | double | |
| 字符串類型 | char、varchar、text | system.String | string |
| nchar、varchar、ntext | system.String | string | |
| 二進(jìn)制字符串類型 | 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 | ? |
?
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的初探EntityFramework——实体类结构映射的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何用c语言从txt文件中读取数据
- 下一篇: gradle下bug修正后问题仍存在解决