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.
DATABASE STRUCTURE
Now create appropriate model in the ASP.NET MVC project for the respective database tables.
MODEL CODE
Category.cs
public class Category
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGenera tedOption.Identity)]
public int CategoryId { get; set; }
[Required]
public string CategoryName { get; set; }
}
SubCategory.cs
public class SubCategory
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOpt ion.Identity)]
public int SubCategoryId { get; set; }
[Required]
public string SubCategoryName { get; set; }
// Foreign key
[Display(Name = "Category")]
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
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.