2010-10-04 281 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;}