2011-06-24 25 views
2

我有一個像這樣的表結構。實體框架一對一關係映射在代碼中展平

Address: 
AddressId int not null primary key identity 
...more columns 

AddressContinental: 
AddressId int not null primary key identity foreign key to pk of Address 
County 
State 

AddressInternational: 
AddressId int not null primary key identity foreign key to pk of Address 
ProvinceRegion 

我沒有控制架構,這只是它的方式。

現在,我想要做的是有一個單一的地址對象。

public class Address 
{ 
    public int AddressId { get; set; } 
    public County County { get; set; } 
    public State State { get; set } 
    public ProvinceRegion { get; set; } 
} 

我想讓EF把它從數據庫中作爲一個實體拉出來。保存時,我想保存單個實體並讓EF知道將其分成三個表格。

我該如何在EF 4.1 Code First中映射?

我一直在四處搜尋,還沒有找到任何符合我的情況。

UPDATE

地址記錄將記錄在Address和一個在任AddressContinentalAddressInternational,但不能同時使用。

回答

1

地址記錄將有創紀錄的 的地址和一個在任 AddressContinental或 AddressInternational,但不能同時使用。

此要求使您的第一個要求無法實現。 @OpticalDelusion向您展示瞭如何映射實體分割的方式,但只有在需要所有部分時才能使用。 EF無法有條件地做到這一點。此外,如果您嘗試保存新的拆分實體,它將始終在所有3個表中創建新記錄。

你需要的是不平坦的對象,但TPT(表每類)繼承,您將有:

public abstract class Address 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

} 

public class AddressContinental : Address 
{ 
    public string Country { get; set; } 
    public string State { get; set; } 
} 

public class AddressInternational : Address 
{ 
    public string ProvinceRegion { get; set; } 
} 

public class Context : DbContext 
{ 
    public DbSet<Address> Addresses { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 

     modelBuilder.Entity<AddressContinental>().ToTable("AddressContinental"); 
     modelBuilder.Entity<AddressInternational>().ToTable("AddressInternational"); 
    } 
} 

}

2

這是我會用的Fluent API。

mb.Entity<Address>() 
    .Map(m => 
    { 
    m.Properties(p => new 
    { 
     p.AddressId 
    }); 
    m.ToTable("Address"); 
    }); 

mb.Entity<Address>() 
    .Map(m => 
    { 
    m.Properties(p => new 
    { 
     p.AddressId, 
     p.County, 
     p.State 
    }); 
    m.ToTable("AddressContinental"); 
    }); 

mb.Entity<Address>() 
    .Map(m => 
    { 
    m.Properties(p => new 
    { 
     p.AddressId, 
     p.ProvinceRegion 
    }); 
    m.ToTable("AddressInternational"); 
    }); 
+0

這似乎只工作(檢索時),如果同時存在在大陸和國際的紀​​錄。地址上會有一條記錄,大陸或國際上有一條記錄,但不是兩條記錄。我沒有提到這一點。我會更新這個問題。 –

+0

我也贊成你的答案。感謝您解決原來的問題。 –