Orm既然是關係映射模型,那學Orm的時侯先學的就是關係映射。所有Orm關係無非就是:一對一,多對一(一對多),多對多。那我們就來對比一下Nh和EF是如何處理數據關係的。
一、 一對一關係映射
一對一的關係映射最好的例子就是一個人都有一個身份證.下面我們就用這個例子。
EF實體:
UserInfo.cs
public class UserInfo
{
public int userid
{
get;
set;
}
public string username
{
get;
set;
}
public int Carid
{
get;
set;
}
public virtual CardInfo CardInfo
{
get;
set;
}
}
CardInfo.cs
public class CardInfo
{
public int Carid
{
get;
set;
}
public string CardName
{
get;
set;
}
}
NH實體:
UserInfo.cs
public class UserInfo
{
Public virtual int userid
{
get;
set;
}
Public virtual string username
{
get;
set;
}
public virtual CardInfo CardInfo
{
get;
set;
}
}
CardInfo.cs
public class CardInfo
{
Public virtual int Carid
{
get;
set;
}
Public virtual string CardName
{
get;
set;
}
}
猛的一看這樣的模型沒錯,不知道EF爲什麼不像NH一樣不能自動創建外鍵(Carid)這樣看起來不怎麼符合領域模型。就因爲這個讓我習慣了好一會兒!比較之我更習慣NH映射的模型.這樣子一看就知道一個人手裏拿了一個身份證.
關係映射:
EF UserInfo映射類:
public class UserInfoConfig : EntityTypeConfiguration<UserInfo>
{
public UserInfoConfig()
{
this.HasKey(p => p.userid);//定義主鍵
this.Property(p => p.username).HasMaxLength(255);//普通屬性映射
this.HasRequired(p => p.CardInfo).WithMany().HasForeignKey(p => p.Carid);//一對一的映射
this.ToTable("T_UserInfo");//生成表
}
}
EF CardInfo映射類:
public class CardInfoConfig : EntityTypeConfiguration<CardInfo>
{
public CardInfoConfig()
{
this.HasKey(p => p.Carid);
this.Property(p => p.CardName).HasMaxLength(255);
this.ToTable("T_CardInfo");
}
}
這樣的映射是不是感覺很爽?我也是這麼認爲,可我還是不大習慣。可能是Nh 用XML映射用多了吧!讓我們看下Nh One to One的映射.
<class name="UserInfo" table="N_UerInfo">
<id name="userid" column="[userid]">
<generator class="native"/>
</id>
<property name="username" type="string" column="[username]" length="255"/>
<one-to-one name="CardInfo" constrained="true"/>
</class>
<class name="CardInfo" table="N_CardInfo">
<id name="Carid" column="[Carid]">
<generator class="native"/>
</id>
<property name="CardName" column="[CardName]" type="string" length="255"/>
</class>
EF和NH關係對比
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
木偶然-2013.7.28
咕咚兒
2019-02-23 00:29:43
Linux系統搭建簡單 D H C P服務
遇見ZZM
2019-02-24 12:53:29
UPLOOKING_APUE
y674526601
2019-02-23 13:21:00
轉:如何用GCC編譯生成動態鏈接庫*.SO文件 動態庫
lazymorning
2019-02-23 12:58:42
使用Excel 2007繪製甘特圖
bokezyyx
2019-02-23 00:42:19
Jquery easyUi Droppable(放置)組件
StringLong
2019-02-23 00:41:59
黑盒測試之錯誤推測法
947154267yjn
2019-02-23 00:37:25
linux下如何防SYN***
曼尼
2019-02-23 00:31:43
如何提高網速20%!
曼尼
2019-02-23 00:31:38
如何使用Percona Toolkit解決Mysql主從不同步問題(1)
冷暖己知
2019-02-23 00:29:40
setScaleType
lwklwc
2019-02-23 00:29:40
android 常見分辨率(mdpi、hdpi 、xhdpi、xxhdpi )及屏幕適配注意事項
lwklwc
2019-02-23 00:29:40