我試圖映射我的實體使用實體框架「代碼優先」,但我有一個映射覆雜類型的問題。在這裏我的簡化的所示例:映射實體框架「代碼優先」
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");
}
}
正被拋出的異常是:「在字典中給出的關鍵是不存在「。
任何人都可以幫助我嗎?
感謝您的回答!因此,在這種情況下,我應該使地址成爲一個聚合(這不會讓我感覺很有意義),或者我不應該將City in Address包含在內,而是將CityId包括在內(可能適用於我,我不一定需要City對象本身)。 – 2010-10-05 14:49:48
其他:可以選擇複雜類型嗎?如果我將空值賦給Address並保存它,它會拋出一個異常,它不能爲空? – 2010-10-05 18:18:47
http://msdn.microsoft.com/en-us/library/bb738472.aspx:複雜類型屬性不能爲空。當調用SaveChanges並遇到空複雜對象時,會發生InvalidOperationException。我想這回答我的問題。問題是我有一個地址是必需的,另一個地址是可選的... – 2010-10-05 18:34:22