2010-10-04 168 views
1

我試圖映射我的實體使用實體框架「代碼優先」,但我有一個映射覆雜類型的問題。在這裏我的簡化的所示例:映射實體框架「代碼優先」

Domain對象的樣子:

public class Customer 
{ 
    public Address DeliveryAddress {get; set;} 
} 

public class Address 
{ 
    public string StreetName {get; set;} 
    public string StreetNumber {get; set;} 
    public City City {get; set;} 
} 

public class City 
{ 
    public int Id {get; set;} 
    public string Name {get; set;} 
} 

和映射:

public class CustomerConfiguration : EntityConfiguration<Customer> 
{ 
    public CustomerConfiguration() 
    { 
     this.HasKey(b => b.Id); 
     this.Property(b => b.Id).IsIdentity(); 

     this.MapSingleType(x => new 
     { 
      Id = x.Id, 
      DeliveryAddress_StreetName = x.DeliveryAddress.StreetName, 
      DeliveryAddress_StreetNumber = x.DeliveryAddress.StreetNumber, 
      DeliveryAddress_CityId = x.DeliveryAddress.City.Id, // this line causes an exception 
     }).ToTable("Customer"); 
    } 
} 

public class AddressConfiguration : ComplexTypeConfiguration<Address> 
{ 
    public AddressConfiguration() 
    {   
     this.Property(b => b.StreetName).HasMaxLength(100).IsRequired().IsUnicode(); 
     this.Property(b => b.StreetNumber).HasMaxLength(6).IsRequired().IsUnicode(); 
} 

public class CityConfiguration : EntityConfiguration<City> 
{ 
    public CityConfiguration() 
    { 
     this.HasKey(b => b.Id); 
     this.Property(b => b.Id).IsIdentity(); 
     this.Property(b => b.Name).IsRequired().HasMaxLength(200).IsUnicode(); 

     this.MapSingleType(x => new 
     { 
      Id = x.Id, 
      Name = x.Name, 
     }).ToTable("City"); 
    } 
} 

正被拋出的異常是:「在字典中給出的關鍵是不存在「。

任何人都可以幫助我嗎?

回答

1

您正試圖將站點實體類型添加到地址複雜類型。這是不可能的。 與實體類似,複雜類型由標量屬性或其他複雜類型屬性組成。由於複雜類型沒有鍵,所以除了父對象外,複雜類型對象不能由實體框架管理。
查看 Complex type article瞭解更多信息。

+0

感謝您的回答!因此,在這種情況下,我應該使地址成爲一個聚合(這不會讓我感覺很有意義),或者我不應該將City in Address包含在內,而是將CityId包括在內(可能適用於我,我不一定需要City對象本身)。 – 2010-10-05 14:49:48

+0

其他:可以選擇複雜類型嗎?如果我將空值賦給Address並保存它,它會拋出一個異常,它不能爲空? – 2010-10-05 18:18:47

+0

http://msdn.microsoft.com/en-us/library/bb738472.aspx:複雜類型屬性不能爲空。當調用SaveChanges並遇到空複雜對象時,會發生InvalidOperationException。我想這回答我的問題。問題是我有一個地址是必需的,另一個地址是可選的... – 2010-10-05 18:34:22

0

您的地址配置沒有將地址連接到城市。

+0

參考,我不認爲我能做到這一點在AddressConfiguration,因爲它是從繼承ComplexTypeConfiguration

...或者我錯了嗎? – 2010-10-05 14:52:49

0

如果您想使用實體框架導航屬性,則需要使用類引用。要做到這一點,你應該使課程參考變得虛擬。因此,在地址城市屬性應該是虛擬的。同時爲便於設置(特別是如果你正在使用MVC)的,你應該包括在一側的ID值保存這樣

public virtual City City {get; set;} 
public int CityId {get; set;}