Tag Archives: System.ComponentModel.DataAnnotations.Schema

Short Walks – Setting up a Foreign Key Relationship in Entity Framework

Having had to search for this for the fiftieth time, I thought I’d document it here, so I knew where to look!

To set-up a foreign key relationship in EF, the first step is to define your classes; for example:

In this case, each Resource has a ResourceType in a simple one-to-many relationship. In the lookup table, in this case: ResourceType, define the key:

public class ResourceType
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    
}

(You’ll need to reference: System.ComponentModel.DataAnnotations)
Then, in the main table, in this case Resource, map a field to the Lookup, and then tell it how to store that in the DB:

public class Resource
{        
    public int Id { get; set; }
 
    public int ResourceTypeId { get; set; }
 
    [ForeignKey("ResourceTypeId")]
    public ResourceType ResourceType { get; set; } 
 
    public string Name { get; set; }
}

(You’ll need to reference: System.ComponentModel.DataAnnotations.Schema)

That’s it. Once you run Add-Migration, you should have a foreign key relationship set-up.