Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map existing fields to a complex type in EFCore

is it possible to take an existing table and map it to an object containing a complex type.

For example:

Table Customer has several address columns but they are simply named AddressLine1, AddressLine2, etc. Not Customer_AddressLine1. Is there a way to still map those fields to a complex type?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example:

public class Customer
{
    public int Id { get; set; }
    public int FirstName { get; set; }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
}

would become:

public class Customer
{
    public int Id { get; set; }
    public int FirstName { get; set; }

    public Address Address { get; set; }
}

public record Address(string Line1, string Line2);

>Solution :

One option would be to provide the column names manually (assuming you are using EF 8 with it’s complex types, the same can be done with owned entities):

modelBuilder.Entity<Customer>()
    .ComplexProperty(entity => entity.Address, builder =>
    {
        builder.Property(c => c.Line1).HasColumnName("AddressLine1");
        builder.Property(c => c.Line2).HasColumnName("AddressLine2");
    });

Other options would be to mess with interceptors and/or IMutableModel (like here)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading