复杂类型:一个模型中的多个实例?

Dav*_*bak 7 c# entity-framework ef-code-first

有没有办法在使用Fluent api模型构建器的同一模型中拥有复杂类型的多个实例?

public class Contact
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public Address PersonalAddress { get; set; }
     public Address BusinessAddress { get; set; }
}

public class Address
{
     public string Street{ get; set; }
     public string City{ get; set; }
     public string PostalCode{ get; set; }
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Configurations.Add(new ContactConfiguration());
     modelBuilder.Configurations.Add(new AddressConfiguration());
}
Run Code Online (Sandbox Code Playgroud)

================================================== ================================

public class AddressConfiguration : ComplexTypeConfiguration<Address>
{
    public AddressConfiguration()
    {

        //props
        this.Property(t => t.Street)
            .IsOptional()
            .HasColumnName("AddressStreet")
            .HasMaxLength(1024);

        this.Property(t => t.PostalCode)
            .IsOptional()
            .HasColumnName("AddressPostalCode")
            .HasMaxLength(64);

        this.Property(t => t.City)
            .IsOptional()
            .HasColumnName("AddressCity")
            .HasMaxLength(512);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mrc*_*ief 1

在 EF 6 中,当您使用相同复杂类型的多个实例时,Code First 会在列名称前加上您的属性名称前缀,例如

PersonalAddress_Street
BusinessAddress_Street
...
Run Code Online (Sandbox Code Playgroud)

等等。您只需要旧版本 EF 的映射。映射选项还允许您用更好的名称替换这些自动生成的名称。

另外,我认为这不是基于您的模型的正确配置代码(可能是拼写错误?):

this.Property(t => t.PersonalAddress.Address.Street)
// should be
this.Property(t => t.PersonalAddress.Street)
Run Code Online (Sandbox Code Playgroud)