Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework (CTP5, Fluent API). Rename column of navigation property

I have two entites:

public class Address
{
        public int Id { get; set; }
 public string FirstName { get; set; 
 public string LastName { get; set; }
}

public partial class Customer
    {
        public int Id { get; set; }
        public string Email { get; set; }
        public string Username { get; set; }

        public virtual Address BillingAddress { get; set; }
        public virtual Address ShippingAddress { get; set; }
    }

Below are mapping classes:

public partial class AddressMap : EntityTypeConfiguration<Address>
    {
        public AddressMap()
        {
            this.ToTable("Addresses");
            this.HasKey(a => a.Id);
        }
    }
public partial class CustomerMap : EntityTypeConfiguration<Customer>
    {
        public CustomerMap()
        {
            this.ToTable("Customer");
            this.HasKey(c => c.Id);

            this.HasOptional<Address>(c => c.BillingAddress);
            this.HasOptional<Address>(c => c.ShippingAddress);
        }
    }

When database is generated, my 'Customer' table has two columns for 'BillingAddress' and 'ShippingAddress' properties. Their names are 'AddressId' and 'AddressId1'. Question: how can I rename them to 'BillingAddressId' and 'ShippingAddressId'?

like image 374
Andrei M Avatar asked Jan 11 '11 17:01

Andrei M


1 Answers

Basically you want to customize the FK column name in an independent association and this code will do this for you:

public CustomerMap()
{
    this.ToTable("Customer");            

    this.HasOptional<Address>(c => c.BillingAddress)
        .WithMany()
        .IsIndependent().Map(m => 
        {
            m.MapKey(a => a.Id, "BillingAddressId");                    
        });

    this.HasOptional<Address>(c => c.ShippingAddress)
        .WithMany()
        .IsIndependent().Map(m =>
        {
            m.MapKey(a => a.Id, "ShippingAddressId");
        });            
}

alt text

like image 102
Morteza Manavi Avatar answered Sep 22 '22 11:09

Morteza Manavi