2012-03-20 103 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