Home > Development > Entity Framework Code First – Specify foreign key name in one to many relationship with fluent API

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):

https://subversion.assembla.com/svn/agilenet/tags/OneToMany

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: