Tag Archives: Explains how to define a Foriegn Key for Property of a Class in Entity Framework code first approach

Defining a Class with Foreign Key in Entity Framework CodeFirst Approach

Introduction

This tip explains how to add a Foreign Key for a column in a model in Entity Framework code first approach with the help of Data Annotations.

Approach

We start with a simple scenario. We know every Book has an Author.

So we build our classes like below:

//Author Class
public class Author
{
       public int AuthorId { get; set; }

       public string AuthorName { get; set; }
}

 

//Book Class
public class Book
{
        public int BookId { get; set; }

        public string BookName { get; set; }

        public int AuthorId { get; set; }
}

And you want to create generate tables that consist of AuthorId foreign key in Book Table.

Like below:

sample9

To achieve the above task, you have to use Data Annotations and the following namespace in your classes:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

So now your code needs to improve as shown below:

//Author Class
public class Author
{
        public Author()
        {

        }

        public int AuthorId { get; set; }

        public string AuthorName { get; set; }

        public ICollection<Book> Books { get; set; }
}
//Book Class
public class Book
{
        public Book()
        {

        }

        public int BookId { get; set; }

        public string BookName { get; set; }

        [ForeignKey("Author")]
        public int AuthorId { get; set; }

        public Author Author { get; set; }
}

Now you can easily generate two tables which are Book and Author with Foreign Key Constraint.

Advertisements