Entity Framework Code First – Specify foreign key name in one to many relationship with fluent API
This post shows how to create a one to many relationship and define the foreign key name. Here we specify the foreign key name using the fluent API.
In this example we have two entities – a Customer and an Address. Each Customer can have one or more Addresses associated with it.
So on the Customer class we have a collection of Addresses. On the Address class we have a property for the Customer it relates to.
public class Customer
{
public int Id { get; set; }
public string CompanyName { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public Customer()
{
Addresses = new List<Address>();
}
}
public class Address
{
public int Id { get; set; }
public string Town { get; set; }
public Customer Customer { get; set; }
}
By default EF will create a foreign key on the Address table named Company_Id. I want it to be named CompanyId. This can be specified as follows using the fluent API:
HasRequired(p => p.Customer)
.WithMany(c => c.Addresses)
.Map(x => x.MapKey("CustomerId"));
To dissect this code:
HasRequired(p => p.Customer) – this is saying that an Address must have a Customer associated with it.
WithMany(c => c.Addresses) – on the other side of the relationship a Customer can have many Addresses.
.Map(x => x.MapKey(“CustomerId”) – this specifies the name of the foreign key column on the Addresses table.
The full code for this post can be found here (easiest to use an SVN client to download this):
Thanks a ton! Your explanation helps a lot
http://stackoverflow.com/questions/6922690/how-to-map-child-entity-to-parent-entity-without-introducing-primitive-type-paren/6925363#6925363