一直以來我都為尋找一個合適的Orm,以前用過NBear感覺不錯,后來轉到Nhibeante特別是Nhibeante的模型映射感覺很強大,也很順手。隨着做了幾個項目之后,發現現在的好多項目是以數據庫為中心的,往往和數據庫設計的標准大相徑庭,這就讓我想起了當前有一面之緣的EF,聽說EF升級到4.2網評反響不錯!一直以來都沒有升級到.net 4.0也許太我Out了吧!呵。。
元旦放假閑在家里沒有事兒,所以看看EF。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>
NH這樣子映射雖然很麻煩但一看就能明白.很喜歡這樣的。有很多人不喜歡XML映射說很麻煩,其實XML的可讀性應該比程序好多了!至少我是這么認為的。一但多起來那就不那么好辦了!
今天就到這了吧!下次再對比其他的幾種關系。