是否可以使用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());
}

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

最佳答案

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

PersonalAddress_Street
BusinessAddress_Street
...

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

另外,我认为这不是基于您的模型的正确配置代码(也许是典型的?):
this.Property(t => t.PersonalAddress.Address.Street)
// should be
this.Property(t => t.PersonalAddress.Street)

关于c# - 复杂类型: multiple instances in one model?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18311680/

10-13 03:18