Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Short Walks — Setting up a Foreign Key Relationship in Entity Framework [Snippet]

DZone 's Guide to

Short Walks — Setting up a Foreign Key Relationship in Entity Framework [Snippet]

If you're looking to find out how to set up a foreign key relationship using .NET's Entity Framework, then this post is for you. Read on for the details.

· Database Zone ·
Free Resource

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.

Topics:
.net ,c# ,entity framework ,databases ,foreign key ,tutorial ,how-to ,database

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}