Entity Framework with Proper Foreign Key Names

Full source code here.

One of the very nice features of Entity Framework is the navigational properties. But it is easy to set them up in a less that optimal way. If you have ever ended up with a foreign key column looking something like – TableName_TableNameId, for example Account_AccountId instead of just AccountId it’s probably because you missed a property on the related entity.

Here is the Account class with a collection of Phones and Addresses.

    public class Account
    {
        public Account()
        {
            Addressess = new List<Address>();
            Phones = new List<Phone>();
        }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid AccountId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual ICollection<Phone> Phones { get; set; }
        public virtual ICollection<Address> Addressess { get; set; }
    }

The Phone has a navigation property to Account, but it does not have a property for the for the AccountId, this results in a foreign key named Account_AccountId in the table. This works just fine, but doesn’t look quite right.

    public class Phone
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid PhoneId { get; set; }
        public string Number { get; set; }

        // No AccountId defined
        // Entity Framework will add a foreign key to Phones table called Account_AccountId

        // Navigation property
        public virtual Account Account { get; set; }
    }

The better way is to add a property for the AccountId to the linked entity, resulting in a foreign key named AccountId.

    public class Address
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid AddressId { get; set; }
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
       
        // This will be the name of the foreign key in the table
        public Guid AccountId { get; set; }
        
        // Navigation property
        public virtual Account Account { get; set; }
    }

Here are the created tables, as you can see the Phones table will has the poorly named foreign key and the Address table has the properly named foreign key.

Good And Bad Foreign Keys

Full source code here.

Leave a Reply

Your email address will not be published. Required fields are marked *