How to create relationships between entities in the Entity Framework Code First Approach

The Entity Framework Code First approach allows us to create a model as a plain class and then the database gets created from the domain model or entity class. In the Code First approach, the database gets created from the classes.

Some advantages of the Entity Framework Code First approach include (as stated in Scott Gu’s blog):

  • Developing without ever having to open a designer or define an XML mapping file
  • Defining your model objects by simply writing “plain old classes” with no base classes required
  • Using a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally overriding the convention-based persistence and using a fluent code API to fully customize the persistence mapping

Rather the delving more into theoretical concepts, in this post we will directly jump into code and create a table and database using the Code First approach. In this post we will learn how we can create entities and a relationship between entities in the Entity Framework Code First approach. In the EF Code First approach, there are two options to create the relationship between entities, through:-Data annotations and  Fluent API

In this post we will use data annotations to create the relationship between entities.

Create database with one table

Let us start with creating a table named Student in a database with the code first approach. The domain class Student can be created as shown in the listing below:

image

As you might have already noticed, the Student class is a plain class. Entity Framework will use the Student class to create the table in the database. The Student class represents the domain entity and it should not have any information or references of the database. Entity Framework will use the Student class to create the Student table.

Once the domain entity class is created, next we need to create a Context class which will inherit the DataContext class. The context class can be created as shown in the listing below:

image

Read the full article on the Infragistics blog

Leave a comment