Renaming a foreign key column in EntityFramework Code-First

I fought this for a while before I finally figured this out, so I thought I’d pass along the info.

The scenario is this: when using a model that references another model via a foreign key and attempting to get it to rename the column to something other than [FK Table]_[FK Table’s Id Column Name] when doing an Update-Database from the package manager console (to build the database).

I searched through a plethora of google links attempting to find a solution, most of which involve using pre-release functionality (community preview-era EF 5). Most solutions attempt to fix this issue via the EF fluent api, but I couldn’t get it to work (I’m not very knowledgeable on that anyway; I find it awfully non-fluent).

I finally found a System.ComponentModel.DataAnnotations attribute, Association, with which I was able to accomplish exactly what I was after.

Given:

public class BaseTable
{
        [Required]
        public Guid BaseTableId { get; set; }

        [Association("RelatedTable", "RelatedTableId", "RelatedTableId")]
        public RelatedTable RelatedTable { get; set; }
        public int? RelatedTableId { get; set; }
}

public class RelatedTable
{
        [Required]
        public int RelatedTableId{ get; set; }
}

When you:

PM> Add-Migration
PM> Update-Database

You will get this table def for BaseTable*:

CREATE TABLE [dbo].[BaseTable] (
    [CharacterId]   INT NOT NULL,
    [RelatedTableId]        INT              NULL,
    CONSTRAINT [PK_dbo.BaseTable] PRIMARY KEY CLUSTERED ([BaseTableId] ASC),
    CONSTRAINT [FK_dbo.BaseTable_dbo.RelatedTable_RelatedTabldId] FOREIGN KEY ([RelatedTableId]) REFERENCES [dbo].[RelatedTable] ([RelatedTableId])
);

Interestingly enough, it still names the constraint [FK Table]_[FK Table’s Id Column Name], but at least the column name itself is now what I want it.

There’s probably an easier/better way to do this, but if so, it’s not easily found with a google search yet.

* I typed the code in this article, so I apologize if some of it doesn’t build, but you get the general idea.

Advertisements
This entry was posted in Development. Bookmark the permalink.

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