Is the Entity Framework a complex type of multiple instances in the same model?

Is there a way to have multiple instances of a complex type inside the same model using the Fluent api model constructor?

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

EDIT (FIND A SOLUTION)

If several instances of a complex type class are used in the same CF model, the configuration of these classes is set at the CF model level as follows:

 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"); } } 
+6
source share
1 answer

With EF 6 Code First, a column name prefix with your property name when you use multiple instances of the same complex type, e.g.

 PersonalAddress_Street BusinessAddress_Street ... 

etc. You only need to map old versions of EF. The matching option also allows you to replace these auto-generated names with something more pleasant.

Also, I don't think this is the correct configuration code based on your models (could there be a typo?):

 this.Property(t => t.PersonalAddress.Address.Street) // should be this.Property(t => t.PersonalAddress.Street) 
+1
source

Source: https://habr.com/ru/post/952018/


All Articles