【问题标题】:Mapping with entity framework "code first"与实体框架“代码优先”进行映射
【发布时间】:2011-04-21 00:08:42
【问题描述】:

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

域对象看起来像:

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

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

谁能帮帮我?

【问题讨论】:

    标签: entity-framework code-first


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答!所以在这种情况下,我应该将地址作为一个聚合(我猜这没有多大意义)或者我不应该在地址中包含 City,而是 CityId(这可能对我有用,我不一定需要 City 对象本身)。
    • 其他:复杂类型可以是可选的吗?如果我将 null 分配给 Address 并保存它,它会抛出一个不可为空的异常?
    • msdn.microsoft.com/en-us/library/bb738472.aspx:复杂类型属性不能为空。调用 SaveChanges 并遇到空复杂对象时会发生 InvalidOperationException。我想这回答了我的问题。问题是我有一个必须的地址和另一个可选的地址...
    【解决方案2】:

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

    【讨论】:

    • 我认为我不能在 AddressConfiguration 中做到这一点,因为它继承自 ComplexTypeConfiguration
      ...还是我错了?
    【解决方案3】:

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

    public virtual City City {get; set;}
    public int CityId {get; set;}
    

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2012-05-18
      • 1970-01-01
      相关资源
      最近更新 更多