我试图映射我的实体使用实体框架“代码优先”,但我有一个映射复杂类型的问题。在这里我的简化的所示例:映射实体框架“代码优先”
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