ASP.NET MVC

How To Create Foreign Key In Code First Approach

In this article, we’ll learn how to create a foreign key in the code first approach.

If you are new to the code first approach, you can refer to this article which covers CRUD operations with a code-first approach in an MVC application.

Here, we are going to create a foreign key in the existing table (MyFirstTables) using migration.

Note: If MyFirstTables is not already existed then it will be created automatically.

Let’s start.

Firstly open the MyFirstTable.cs file and add the code in it.

using System;  
using System.Collections.Generic;  
using System.ComponentModel.DataAnnotations;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
 
namespace Code_First_Demo.Models  
{  
    public class MyFirstTable  
    {  
        [Key]  
        public int ID { get; set; }  
        public string Name { get; set; }  
        public int Age { get; set; }
        public int CID { get; set; }
        public CountryTable Country { get; set; }
    }
    public class CountryTable
    {  
        [Key]  
        public int CID { get; set; }  
        public string CName { get; set; }
    }
}

Now, open the CDBContext.cs  file and add the code in it.

 
using Code_First_Demo.Models;  
using System;  
using System.Collections.Generic;  
using System.Data.Entity;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;
 
namespace Code_First_Demo.Repository  
{  
    public class CDBContext : DbContext  
    {  
        public CDBContext() : base("StringDBContext")  
        {  
        }  
        public DbSet<MyFirstTable> MyFirstTable { get; set; }
        public DbSet<CountryTable> CountryTable { get; set; }
    }  
}

Now, open the package manager console to fire the commands.

  • Add-Migration MigrationName

Note: You can put any migration name you choose.

Add-Migration AddForeignKey
  • Update-Database

Note: This command will Create/modify your database.

Update-Database

The above example depicts a property name CID in MyFirstTable entity matches with the primary key property of CountryTable entity, so CID in MyFirstTable entity will automatically become a foreign key property, as shown below.

For a foreign key, the [ForeignKey] attribute overrides the default convention. It allows us to specify in the dependent entity the foreign key property whose name does not match with the primary key property of the principal entity.

The [ForeignKey] attribute on the foreign key property in the dependent entity and the related navigation property name can be specified as a parameter as shown in the example below.

Now just open the MyFirstTable.cs file and replace the code in it.

using System;  
using System.Collections.Generic;  
using System.ComponentModel.DataAnnotations;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.ComponentModel.DataAnnotations.Schema;
 
namespace Code_First_Demo.Models  
{  
    public class MyFirstTable  
    {  
        [Key]  
        public int ID { get; set; }  
        public string Name { get; set; }  
        public int Age { get; set; }

        [ForeignKey("Country")]
        public int CID { get; set; }
        public CountryTable Country { get; set; }
    }
    public class CountryTable
    {  
        [Key]  
        public int ID { get; set; }  
        public string CName { get; set; }
    }
}

As we can see CountryTable has a primary key, named ID. Where MyFirstTable has a foreign key, named CID.

That’s it.

 

Also, check How To Use FOREIGN KEY Constraint In SQL

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

View Comments

  • Nice and simple explanation.
    I have a question though Yasin, how does the framework know that "CountryTable" is CountryTables (in plural) in SQL database ?

    Thanks !

  • [ForeignKey("Country")] // not Country , CountryTable am i correct?
    public int CID { get; set; }
    public CountryTable Country { get; set; }

    • NO
      As per ForeignKeyAttribute definition, we must have to put navigation property name (Not the table name)

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago