2

我正在尝试使用实体框架“代码优先”映射我的实体,但我在映射复杂类型时遇到了问题。这是我的简化示例:

域对象如下所示:

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");
    }
}

抛出的异常是:“字典中不存在给定的键。”

谁能帮我?

4

3 回答 3

2

您正在尝试将站点实体类型添加到地址复杂类型。这是不可能的。 与实体一样,复杂类型由标量属性或其他复杂类型属性组成。因为复杂类型没有键,所以除了父对象之外,复杂类型对象不能由实体框架管理。
查看复杂类型文章以获取更多信息。

于 2010-10-05T12:57:40.487 回答
0

您的地址配置未将地址连接到城市。

于 2010-10-05T09:09:42.237 回答
0

如果您想使用实体框架导航属性,则需要使用类引用。为此,您应该将类​​引用设为虚拟。因此,在 Address the City 属性中应该是虚拟的。此外,为了便于设置(特别是如果您使用 MVC),您应该在保存引用的一侧包含 ID 值,如下所示

public virtual City City {get; set;}
public int CityId {get; set;}
于 2011-05-13T15:38:47.033 回答