开发者

Entity framework 4 - custom complex type mapping

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 cre开发者_运维百科ate 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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜