11

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?

3
  • 1
    Don't use CTP5. Install a new version called 4.1 RC - microsoft.com/downloads/en/… Commented Mar 16, 2011 at 8:11
  • I thought CTP5 was the "final"? Does the new version fix this issue? Commented Mar 16, 2011 at 15:57
  • No, CTPs are never considered to be a final version. That said, EF 4.1 RC seems to be a more bug fixing release than a fundamental change over CTP5. Commented Mar 16, 2011 at 18:42

1 Answer 1

14

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");         
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

to keep entirely within the FluentAPI, you should drop the ComplexType annotation and use modelBuilder.ComplexType<Address>(); UPDATE: just submitted an edit to do just that since this is an old post.... it's pending

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.