Map existing fields to a complex type in EFCore

30 Views Asked by At

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?

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

There are 1 best solutions below

0
Guru Stron On BEST ANSWER

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)