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

Related entities in Entity Framework Code First approach

In this post we will learn to create relationship between entities in the Entity Framework Code First approach.

Setting up

We are going to create three tables and set up the relationship between them.

  1. BankUser
  2. BankUserAccount
  3. Nomniee

To create tables we will create entities further in the post. For table creation the context class has been created as follows.

 

public class Context : DbContext
    {

        public Context ()
	        {
                     Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>());
	        }

        public DbSet<BankUser> BankUser {get;set;}
        public DbSet<BankUserAccount> BankUserAccount  {get;set;}

        public DbSet<Nominee> Nomniee { get; set; }
    }


Keep in mind that, very likely you will get build error if you try to build the project as of now.

One to many relationship

Let us say we have two entities. One for the bank user and another for the bank user’s accounts. A bank user can have any numbers of the bank accounts. Typically a bank user will have following properties

    public class BankUser
    {
   
        public string   ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set;  }
        public string Sex { get; set; }

    }


A bank user can have any number of bank accounts. To map this we will have to create one NAVIGATION PROPERTY in the BankUser class. A navigation property holds entities which are related to this particular entity. An entity can have any number of related entities. Since BankUserAccount(we will create this entity later) is a related entity of the BanUser entity. So it will be as the navigation property of the BankUser account. One bank user can have any numbers of bank user account, so we will have to create collection BankUserAccount entity as the navigation property of the BankUser entity. To do this, modify the above class as below:

public class BankUser
    {
   
        public string   ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set;  }
        public string Sex { get; set; }

        public virtual ICollection<BankUserAccount> Accounts { get; set; }

    }

We define navigation property as virtual such that while reading the data we can take advantage of the entity framework lazy loading feature.

public class BankUserAccount
    {
        public string ID { get; set; }
        public double Amount { get; set; }
        public string? EmergencyContact { get; set; }
        public DateTime LastTransaction { get; set; }
        public virtual BankUser BankUser { get; set; }
    }

By this time relationship between the two tables has been created as shown below:

image

And BankUserAccount table is created as follows:

image

One to one relationship

In one to one relationship between two entities, one act as the primary entity and another as the dependent entity. Primary key of the primary entity will be used as foreign key of the dependent entity. An entry cannot be created in the dependent entity without having a reference in the primary entity. Okay enough of theory let us go ahead and see an example. So far we have seen that a bank user can have multiple bank accounts. However a particular bank account can have only one nominee. So primary key of BankUserAccount entity will act as foreign key of the Nominee entity. You can create a Nominee entity with the foreign key as shown below:

 

  public class Nominee
    {


       public string ID { get; set; }

       public string Name { get; set; }

       public string Age { get; set; }      
       [Required]
       public virtual BankUserAccount BankUserAccount { get; set; }
    }


As you see navigation property BankUserAccount is attributed with the REQUIRED. So we cannot create a Nominee entity without providing the bank user account.

By this time relationship between the two tables has been created as shown below:

image

And the Nominee table is created as below:

image

As you can see that in the Nominee table BankUserAccountID is the foreign key. Primary key of the Nominee table is different than the foreign key. So one person can be nominee of any number of bank accounts.

Other options could be, and in my opinion absolute one to one relationship. In this scenario one person can only be nominee to one bank user account. In this case you will have to modify the BankUserAccount as follows:

 

public class BankUserAccount
    {
        public string ID { get; set; }
        public double Amount { get; set; }
        public string EmergencyContact { get; set; }
        public DateTime LastTransaction { get; set; }
        public virtual BankUser BankUser { get; set; }
        public virtual Nominee Noinee { get; set; }
    }


By this time relationship between the two tables has been created as shown below:

image

And the Nominee table is modified as below:

image

Now to create the database in the local db you don’t need to modify the connection string and make a use of context class as below,

 

Context context = new Context();
            BankUser c1 = new BankUser
            {
                ID=  "C5",
                Age = 32,
                Name= "DJ",
                Sex= "Male",
               

            };
            context.BankUser.Add(c1);
            context.SaveChanges();

            var result = context.BankUser.ToList();
            foreach (var r in result)
            {
                Console.WriteLine(r.Name);
            }
            Console.ReadKey(true);

In this way you can create relationship between entities in the entity framework. I hope this post is useful.

Happy coding.