Question

I have a poorly written legacy database schema that I'm working with via EF Code First. I'm currently mapping POCO entities and would like to create an "Address" complex type and use this everywhere where street address information is stored. Unfortunately, not all of the address fields are named the same in the database (ie. one table might have "Address1" while another table will have "Street1" even though they refer to the same thing.

Is there a way to create custom mappings for a complex type based on a given entity? What does that mapping look like?

Was it helpful?

Solution

Yes, you can achieve that with fluent API. Here is an example:

public class User
{
    public int UserId { get; set; }   
    public Address Address { get; set; }
}

public class Customer
{
    public int CustomerId { get; set; }   
    public Address Address { get; set; }
}

[ComplexType]
public class Address
{
    public string Street { get; set; }    
    public string City { get; set; }
}

public class Context : DbContext
{    
    public DbSet<User> Users { get; set; }
    public DbSet<Customer> Customers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {       
        modelBuilder.Entity<User>().Property(u => u.Address.Street)
                                   .HasColumnName("UserStreet");

        modelBuilder.Entity<Customer>().Property(u => u.Address.Street)
                                       .HasColumnName("CustomerStreet");         
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top