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

Compliant Database DevOps and the role of DevSecOps DevOps is becoming the new normal in application development, and DevSecOps is now entering the picture. By balancing the desire to release code faster with the need for the same code to be secure, it addresses increasing demands for data privacy. But what about the database? How can databases be included in both DevOps and DevSecOps? What additional measures should be considered to achieve truly compliant database DevOps? This whitepaper provides a valuable insight. Get the whitepaper

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.

Compliant Database DevOps and the role of DevSecOps DevOps is becoming the new normal in application development, and DevSecOps is now entering the picture. By balancing the desire to release code faster with the need for the same code to be secure, it addresses increasing demands for data privacy. But what about the database? How can databases be included in both DevOps and DevSecOps? What additional measures should be considered to achieve truly compliant database DevOps? This whitepaper provides a valuable insight. Get the whitepaper

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 }}