ASP.NET MVC > Models

Primary key and Foreign key relationship in Model in ASP.NET MVC

How to specify primary key and foreign keys relationship to the Models in ASP.NET MVC?

To demonstrate primary key and foreign keys relationship to the Model in ASP.NET MVC, we are going to create two tables with following structure and relationship. 

  • Categories – has primary key as “CategoryId” 
  • SubCategories- has foreign key as “CategoryId” that is related with “CategoryId” of Categories table.


Now create appropriate model in the ASP.NET MVC project for the respective database tables. 



public class Category 
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGenera tedOption.Identity)]
public int CategoryId { get; set; }

public string CategoryName { get; set; }


 public class SubCategory 
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOpt ion.Identity)]
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }

// Foreign key
[Display(Name = "Category")]
public int CategoryId { get; set; }


public virtual Category Categories { get; set; }

Notice the CategoryId property of the SubCategory model. As this is the foreign key from the primary key table Category so we have specified the ForeignKey attribute to the primary key Category model property by specifying the name of the property as parameter. The benefit of this is that while scaffolding Controller and Views for SubCategory, the SubCategory create view will automatically show a dropdown of Categories to select as shown below. 

Notice the CategoryId dropdown in above create view of SubCategory, this is coming because of foreign key relationship specified in the SubCateogry model. 

 Views: 14801 | Post Order: 41

Write for us