2012-03-20 86 views
0

在我正在處理的網站數據庫中,我有兩個表格,例如:Country & CountryLocale。這兩個表包含以下幾列:將多個表映射到Entity Framework中的單個實體

國家:ID,經度,緯度 CountryLocale:身份證,CountryId,國家或地區名稱,CultureId

我要的是:
- 當我取回的國家,我想包含的實體:CountryId,CountryName,CultureId,Latitude &經度。
- 當我創建一個新的國家時,要向Table Country插入一條記錄,向Table CountryLocale插入一條記錄。
- 當我創建一個新的國家語言環境,創建一個記錄裏面CountryLocale只有

等等

這是可以實現的? 感謝

回答

1

您可以使用實體拆分爲部分實現,你可以定義你的子實體。 CountryLocale將使用Country的PK作爲其PK。如果沒有Country,則無法插入CountryLocale。基本上它是一個單獨的實體分成多個表。

modelBuilder.Entity<Country>() 
     .Map(mc => 
     { 
      mc.Properties(n => new 
      { 
       n.Id, 
       n.Longitude, 
       n.Latitude 
      }); 
      mc.ToTable("Country"); 
     }) 
     .Map(mc => 
     { 
      mc.Properties(n => new 
      { 
       n.CountryName, 
       n.CultureId 
      }); 
      mc.ToTable("CountryLocale"); 
     }); 
+0

CountryId不能是CountryLocale的PK,因爲我可能每個國家有多個CountryLocale記錄。上面的代碼在哪裏?請更多插圖。謝謝 – Bill 2012-03-20 14:52:09

+0

我沒有使用CodeFirst的方式。我有數據庫已經存在,並使用實體框架。 – Bill 2012-03-20 14:54:26

+0

@bhaidar然後顯然你不能將屬性映射到單個實體。你將不得不使用一對多映射。 – Eranga 2012-03-20 14:56:19

0

使用鑑別(每個層次結構表)

modelBuilder.Entity<CountryBase>() 
    .Map<Country>(c => c.Requires("Type").HasValue((int)CountryType.Country)) 
    .Map<CountryLocale>(c => c.Requires("Type").HasValue((int)CountryType.CountryLocale)); 

,併爲你喜歡

+0

請問我有更多的插圖嗎?謝謝 – Bill 2012-03-20 14:49:12

相關問題