有没有一种方法可以使用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)
使用数据注释[ComplexType]可能更简单,EF将自动设置名称。使用您的示例:
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; }
}
[ComplexType]
public class Address{
public string Street{ get; set; }
public string City{ get; set; }
public string PostalCode{ get; set; }
}
EF在Contact Entity中创建所有字段,并将其命名为:个人地址树、业务地址树、个人地址城市、业务地址城市等…
(问题中自动回答的部分转换为真实答案)
如果在同一个CF模型中使用多个复杂类型的类实例,则这些类的配置设置在CF模型级别,如下所示:
public class ContactConfiguration : EntityTypeConfiguration<Contact>
{
public ContactConfiguration()
{
//props for PersonalAddress instance of Address complex type class
this.Property(t => t.PersonalAddress.Address.Street)
.HasColumnName("PersonalAddressStreet");
this.Property(t => t.PersonalAddress.Address.PostalCode)
.HasColumnName("PersonalAddressPostalCode");
this.Property(t => t.PersonalAddress.Address.City)
.HasColumnName("PersonalAddressCity");
//props for BusinessAddress instance of Address complex type class
this.Property(t => t.BusinessAddress.Address.Street)
.HasColumnName("BusinessAddressStreet");
this.Property(t => t.BusinessAddress.Address.PostalCode)
.HasColumnName("BusinessAddressPostalCode");
this.Property(t => t.BusinessAddress.Address.City)
.HasColumnName("BusinessAddressCity");
}
}