用实体框架映射“代码优先”

时间:2010-10-04 20:25:16

标签: entity-framework code-first

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

域对象看起来像:

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

抛出的异常是:'字典中没有给定的密钥。'

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

您正尝试将网站实体类型添加到地址复杂类型。这是不可能的。 与实体类似,复杂类型由标量属性或其他复杂类型属性组成。由于复杂类型没有键,因此除了父对象之外,实体框架不能管理复杂类型对象。
有关详细信息,请查看 Complex type article

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果要使用“实体框架”导航属性,则表示类引用。要做到这一点,你应该使类引用虚拟。所以在Address the City属性应该是虚拟的。另外为了便于设置(特别是如果你使用MVC),你应该在包含引用的一侧包含ID值,如下所示

public virtual City City {get; set;}
public int CityId {get; set;}
相关问题