Relationship in Entity Framework Using Code First Approach With Fluent API

Introduction

A relationship, in the context of databases, is a situation that exists between two relational database tables when one table has a foreign key that references the primary key of the other table. Relationships allow relational databases to split and store data in various tables, while linking disparate data items. For example if we want to store information about a Customer and his Order then we need to create two tables, one for the Customer and another for the Order. Both tables, Customer and Order, will have the relationship one-to-many so whenever we retrieve all orders of a customer then we can easily retrieve them.

There are several types of database relationships. In this article I will cover the following:

  • One-to-One Relationships
  • One-to-many or Many to One Relationships
  • Many-to-Many Relationships

Entity Framework Code First allows us to use our own domain classes to represent the model that Entity Framework relies on to perform querying, change tracking and updating functions. The Code First approach follows conventions over the configuration but it also gives us two ways to add a configuration on over classes. One is using simple attributes called DataAnnotations and another is using Code First's Fluent API, that provides you with a way to descried configuration imperatively, in code. This article will focus on tuning up the relationship in the Fluent API.

To understand the relationship in the Entity Framework Code First approach, we create an entity and define their configuration using the Fluent API. We will create two class library projects, one library project (EF.Core) has entities and another project (EF.Data) has these entities configuration with DbContext. We also create a unit test project (EF.UnitTest) that will be used to test our code. We will use the following classes that are in a class diagram to explain the preceding three relationships.



Figure 1.1: Class Diagram for Entities.

As in the preceding class diagram the BaseEntity class is a base class that is inherited by each other class. Each derived entity represents each database table. We will use two derived entities combination from the left side to explain each relationship type and that's why we create six entities.

So first of all we create the BaseEntity class that is inherited by each derived entity under the EF.Core class library project.

  1. using System;  
  2.   
  3. namespace EF.Core  
  4. {  
  5.   public abstract  class BaseEntity  
  6.     {  
  7.         public Int64 ID { getset; }  
  8.         public DateTime AddedDate { getset; }  
  9.         public DateTime ModifiedDate { getset; }  
  10.         public string IP { getset; }  
  11.     }  

We use navigation properties to access a related entity object from one to another. The navigation properties provide a way to navigate an association between two entity types. Every object can have a navigation property for every relationship in which it participates. Navigation properties allow you to navigate and manage relationships in both directions, returning either a reference object (if the multiplicity is either one or zero-or-one) or a collection (if the multiplicity is many).

Now let's see each relationship one-by-one.

Our Roadmap towards Learning MVC with Entity Framework. 
One-to-One Relationship

Both tables can have only one record on either side of the relationship. Each primary key value relates to only one record (or no records) in the related table. Keep in mind that this kind of relationship is not very common and most one-to-one relationships are forced by business rules and don't flow naturally from the data. In the absence of such a rule, you can usually combine both tables into one table without breaking any normalization rules.

To understand one-to-one relationships, we create two entities, one is User and another is UserProfile. One user can have a single profile, a User table that will have a primary key and that same key will be both primary and foreign keys for the UserProfile table. Let’s see Figure 1.2 for one-to-one relationship.



Figure 1.2: One-to-One Relationship

Now we create both entities User and UserProfile in the EF.Core project under the Data folder. Our User class code snippet is as in the following:
  1. namespace EF.Core.Data  
  2. {  
  3.    public class User : BaseEntity  
  4.     {  
  5.         public string UserName { getset; }  
  6.         public string Email { getset; }  
  7.         public string Password { getset; }  
  8.         public UserProfile UserProfile { getset; }  
  9.     }  
  10. } 

The UserProfile class code snippet is as in the following:

  1. namespace EF.Core.Data  
  2. {  
  3.    public class UserProfile : BaseEntity   
  4.     {  
  5.         public string FirstName { getset; }  
  6.         public string LastName { getset; }  
  7.         public string Address { getset; }  
  8.         public virtual User User { getset; }  
  9.     }  

As you can see in the preceding, both code snippets that each entity is using another entity as a navigation property so that you can access the related object from each other.

Now we define the configuration for both entities that will be used when the database table will be created by the entity. The configuration defines another class library project EF.Data under the Mapping folder. Now create two configuration classes for each entity. For the User entity we create the UserMap entity.

  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity.ModelConfiguration;  
  3. using EF.Core.Data;  
  4.   
  5. namespace EF.Data.Mapping  
  6. {  
  7.     public class UserMap : EntityTypeConfiguration<User>  
  8.     {  
  9.         public UserMap()  
  10.         {  
  11.             //Key  
  12.             HasKey(t => t.ID);  
  13.   
  14.             //Fields  
  15.             Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  16.             Property(t => t.UserName).IsRequired().HasMaxLength(25);  
  17.             Property(t => t.Email).IsRequired();  
  18.             Property(t => t.AddedDate).IsRequired();  
  19.             Property(t => t.ModifiedDate).IsRequired();  
  20.             Property(t => t.IP);  
  21.   
  22.             //table  
  23.             ToTable("Users");  
  24.         }  
  25.     }  

We will use the same way to create the configuration for other entities as for the User. EntityTYpeConfiguration<T> is an important class that allows configuration to be performed for an entity type in a model. This is done using the modelbuilder in an override of the OnModelCreate method. The Constructor of the UserMap class uses the Fluent API to map and configure properties in the table. So let's see each method used in the constructor one-by-one.

  1. HasKey(): The Haskey() method configures a primary key on table.
  2. Property() : The Property method configures attributes for each property belonging to an entity or complex type. It is used to obtain a configuration object for a given property. The options on the configuration object are specific to the type being configured.
  3. HasDatabaseGeneratedOption: It configures how values for the property are generated by the database.
  4. DatabaseGeneratedOption.Identity: DatabaseGeneratedOption is the database annotation. It enumerates a database generated option. DatabaseGeneratedOption.Identity is used to create an auto-increment column in the table by a unique value.
  5. ToTable(): Configures the table name that this entity type is mapped to.

Now create the UserProfile configuration class, the UserProfileMap class.

  1. using System.Data.Entity.ModelConfiguration;  
  2. using EF.Core.Data;  
  3.   
  4. namespace EF.Data.Mapping  
  5. {  
  6.     public class UserProfileMap : EntityTypeConfiguration<UserProfile>  
  7.     {  
  8.         public UserProfileMap()  
  9.         {  
  10.             //key  
  11.             HasKey(t => t.ID);  
  12.   
  13.             //fieds  
  14.             Property(t => t.FirstName);  
  15.             Property(t => t.LastName);  
  16.             Property(t => t.Address).HasMaxLength(100).HasColumnType("nvarchar");  
  17.             Property(t => t.AddedDate);  
  18.             Property(t => t.ModifiedDate);  
  19.             Property(t => t.IP);  
  20.   
  21.             //table  
  22.             ToTable("UserProfiles");  
  23.   
  24.             //relationship  
  25.             HasRequired(t => t.User).WithRequiredDependent(u => u.UserProfile);  
  26.         }  
  27.     }  

In the code snippet above we defined a one-to-one relationship between both User and UserProfiles entities. This relationship is defined by the Fluent API using the HasRequired() and WithRequiredDependent() methods so these methods are as in the following:

  1. HasRequired(): Configures a required relationship from this entity type. Instances of the entity type will not be able to be saved to the database unless this relationship is specified. The foreign key in the database will be non-nullable. In other words UserProfile can’t be saved independently without User entity.
  2. WithRequiredDependent(): (from the MSDN) Configures the relationship to be required: required without a navigation property on the other side of the relationship. The entity type being configured will be the dependent and contain a foreign key to the principal. The entity type that the relationship targets will be the principal in the relationship.

Now define the connection string in App.config file under EF.Data Project so that we can create Database with appropriate name. The connectionstring is:

  1. <connectionStrings>  
  2.     <add name="DbConnectionString" connectionString="Data Source=sandeepss-PC;Initial Catalog=EFCodeFirst;User ID=sa; Password=*******" providerName="System.Data.SqlClient" />  
  3. </connectionStrings> 

Now we create a context class EFDbContext (EFDbContext.cs) that inherits the DbContext class. In this class we override the OnModelCreating() method. This method is called when the model for a context class (EFDbContext) has been initialized, but before the model has been locked down and used to initialize the context such that the model can be further configured before it is locked down. The following is the code snippet for the context class.

  1. using System;  
  2. using System.Data.Entity;  
  3. using System.Data.Entity.ModelConfiguration;  
  4. using System.Linq;  
  5. using System.Reflection;  
  6.   
  7. namespace EF.Data  
  8. {  
  9.    public class EFDbContext : DbContext  
  10.     {  
  11.        public EFDbContext()  
  12.            : base("name=DbConnectionString")  
  13.        {  
  14.            
  15.        }  
  16.          
  17.        protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  18.        {  
  19.             var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()  
  20.            .Where(type => !String.IsNullOrEmpty(type.Namespace))  
  21.            .Where(type => type.BaseType != null && type.BaseType.IsGenericType  
  22.                 && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));  
  23.            foreach (var type in typesToRegister)  
  24.            {  
  25.                dynamic configurationInstance = Activator.CreateInstance(type);  
  26.                modelBuilder.Configurations.Add(configurationInstance);  
  27.            }  
  28.            base.OnModelCreating(modelBuilder);  
  29.        }  
  30.     }  

As you know the EF Code First approach follows convention over configuration so in the constructor we just pass the connection string name same as an App.Config file and it connects to that server. In the OnModelCreating() method, we used a reflection to map an entity to its configuration class in this specific project.

We create a Unit Test Project EF.UnitTest to test the code above. We create a test class UserTest that has a test method UserUserProfileTest(). This method creates a database and populates User and UserProfile tables as per their relationship. The following is the code snippet for the UserTest class.

  1. using System;  
  2. using System.Data.Entity;  
  3. using EF.Core.Data;  
  4. using EF.Data;  
  5. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  6.   
  7. namespace EF.UnitTest  
  8. {  
  9.     [TestClass]  
  10.     public class UserTest  
  11.     {  
  12.         [TestMethod]  
  13.         public void UserUserProfileTest()  
  14.         {  
  15.             Database.SetInitializer<EFDbContext>(new CreateDatabaseIfNotExists<EFDbContext>());  
  16.             using (var context = new EFDbContext())  
  17.             {  
  18.                 context.Database.Create();  
  19.                 User user = new User  
  20.                 {  
  21.                     UserName = "ss_shekhawat",  
  22.                     Password = "123",  
  23.                     Email = "[email protected]",  
  24.                     AddedDate = DateTime.Now,  
  25.                     ModifiedDate = DateTime.Now,  
  26.                     IP = "1.1.1.1",  
  27.                     UserProfile = new UserProfile  
  28.                     {  
  29.                         FirstName ="Sandeep",  
  30.                         LastName ="Shekhawat",  
  31.                         Address="Jaipur and Jhunjhunu",                          
  32.                         AddedDate = DateTime.Now,  
  33.                         ModifiedDate = DateTime.Now,  
  34.                         IP = "1.1.1.1"  
  35.                     },  
  36.                 };  
  37.                 context.Entry(user).State = System.Data.EntityState.Added;  
  38.                 context.SaveChanges();  
  39.             }  
  40.         }  
  41.     }  

Now run the Test method and you get your table in the database with data. Run a select query in the database and get results like.

  1. SELECT [ID],[UserName],[Email],[Password],[AddedDate],[ModifiedDate],[IP]FROM [EFCodeFirst].[dbo].[Users]  
  2.     
  3. SELECT [ID],[FirstName],[LastName],[Address],[AddedDate]      ,[ModifiedDate],[IP] FROM [EFCodeFirst].[dbo].[UserProfiles] 

Now execute the preceding query and then you will get results as in the following figure.



Figure 1.3: Result of User and UserProfile.

That’s it for One-to–One relationships.

One-to-many Relationship

The primary key table contains only one record that relates to none, one, or many records in the related table. This is the most commonly used type of relationship.

To understand this relationship, consider an e-commerce system where a single user can make many orders so we define two entities, one for the customer and another for the order. Let’s see the following figure.



Figure 1.4 One-to-many Relationship

The customer entity is as in the following:

  1. using System.Collections.Generic;  
  2.   
  3. namespace EF.Core.Data  
  4. {  
  5.   public  class Customer : BaseEntity   
  6.     {  
  7.       public string Name { getset; }  
  8.       public string Email { getset; }  
  9.       public virtual ICollection<Order> Orders { getset; }  
  10.     }  

The Order entity code snippet is as in the following:

  1. using System;  
  2.   
  3. namespace EF.Core.Data  
  4. {  
  5.     public class Order : BaseEntity  
  6.     {  
  7.         public byte Quanatity { getset; }  
  8.         public Decimal Price { getset; }  
  9.         public Int64 CustomerId { getset; }  
  10.         public virtual Customer Customer { getset; }  
  11.     }  

You have noticed the navigation properties in the code above. The Customer entity has a collection of Order entity types and the Order entity has a Customer entity type property, that means a customer can make many orders.

Now create a class, the CustomerMap class in the EF.Data project to implement the Fluent API configuration for the Customer class.

  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity.ModelConfiguration;  
  3. using EF.Core.Data;  
  4.   
  5. namespace EF.Data.Mapping  
  6. {  
  7.    public class CustomerMap : EntityTypeConfiguration<Customer>  
  8.     {  
  9.        public CustomerMap()  
  10.        {  
  11.            //key  
  12.            HasKey(t => t.ID);  
  13.   
  14.            //properties  
  15.            Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  16.            Property(t => t.Name);  
  17.            Property(t => t.Email).IsRequired();  
  18.            Property(t => t.AddedDate).IsRequired();  
  19.            Property(t => t.ModifiedDate).IsRequired();  
  20.            Property(t => t.IP);  
  21.   
  22.            //table  
  23.            ToTable("Customers");  
  24.        }  
  25.     }  

Now create another mapping class for the Order entity configuration.

  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity.ModelConfiguration;  
  3. using EF.Core.Data;  
  4.   
  5. namespace EF.Data.Mapping  
  6. {  
  7.    public class OrderMap : EntityTypeConfiguration<Order>  
  8.     {  
  9.        public OrderMap()  
  10.        {  
  11.            //key  
  12.            HasKey(t => t.ID);  
  13.   
  14.            //fields  
  15.            Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  16.            Property(t => t.Quanatity).IsRequired().HasColumnType("tinyint");  
  17.            Property(t => t.Price).IsRequired();  
  18.            Property(t => t.CustomerId).IsRequired();  
  19.            Property(t => t.AddedDate).IsRequired();  
  20.            Property(t => t.ModifiedDate).IsRequired();  
  21.            Property(t => t.IP);  
  22.   
  23.            //table  
  24.            ToTable("Orders");  
  25.   
  26.            //relationship  
  27.            HasRequired(t => t.Customer).WithMany(c => c.Orders).HasForeignKey(t => t.CustomerId).WillCascadeOnDelete(false);  
  28.        }  
  29.     }  

The code above shows that a Customer is required for each order and the Customer can make multiple orders and relationships between both make by foreign key CustomerId. Here we use four methods to define the relationship between both entities. The WithMany method, that allows us to indicate which property in Customer contains the Many relationship. We add to that the HasForeignKey method to indicate which property of Order is the foreign key pointing back to customer. The WillCascadeOnDelete() method Configures whether or not cascade delete is on for the relationship.

No we create another unit test class in the EF.UnitTest Project to test the code above. Let’s see the test method that inserts data for the customer that has two orders.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using EF.Core.Data;  
  5. using EF.Data;  
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  7.   
  8. namespace EF.UnitTest  
  9. {  
  10.     [TestClass]  
  11.     public class CustomerTest  
  12.     {  
  13.         [TestMethod]  
  14.         public void CustomerOrderTest()  
  15.         {  
  16.              Database.SetInitializer<EFDbContext>(new CreateDatabaseIfNotExists<EFDbContext>());  
  17.              using (var context = new EFDbContext())  
  18.              {  
  19.                  context.Database.Create();  
  20.                  Customer customer = new Customer  
  21.                                      {  
  22.                                          Name = "Raviendra",  
  23.                                          Email = "[email protected]",  
  24.                                          AddedDate = DateTime.Now,  
  25.                                          ModifiedDate = DateTime.Now,  
  26.                                          IP = "1.1.1.1",  
  27.                                          Orders = new List<Order>{  
  28.                                             new Order  
  29.                                             {  
  30.                                                 Quanatity =12,  
  31.                                                 Price =15,  
  32.                                                 AddedDate = DateTime.Now,  
  33.                                                 ModifiedDate = DateTime.Now,  
  34.                                                  IP = "1.1.1.1",  
  35.                                             },  
  36.                                             new Order  
  37.                                             {  
  38.                                                 Quanatity =10,  
  39.                                                 Price =25,  
  40.                                                 AddedDate = DateTime.Now,  
  41.                                                 ModifiedDate = DateTime.Now,  
  42.                                                  IP = "1.1.1.1",  
  43.                                             }  
  44.                                         }  
  45.                                      };  
  46.                  context.Entry(customer).State = System.Data.EntityState.Added;  
  47.                  context.SaveChanges();  
  48.              }  
  49.         }  
  50.     }  

Now run the Test method and you get your table in the database with data. Run a select query in the database and get results like.

  1. SELECT [ID],[Name],[Email],[AddedDate],[ModifiedDate],[IP]FROM [EFCodeFirst].[dbo].[Customers]  
  2. SELECT [ID],[Quanatity],[Price],[CustomerId],[AddedDate],[ModifiedDate],[IP]FROM [EFCodeFirst].[dbo].[Orders] 



Figure 1.5: Customer and Order Data.

Many-to-Many Relationship

Each record in both tables can relate to any number of records (or no records) in the other table. Many-to-many relationships require a third table, known as an associate or linking table, because relational systems can't directly accommodate the relationship.

To understand this relationship, consider an online course system where a single student can join many courses and a course can have many students so we define two entities, one for the student and another for the course. Let’s see the following figure for the Many-to-Many relationship.



Figure 1.6: Many-to-Many Relationship.

The Student entity is as in the following code snippet that is defined under EF.Core Project.

  1. using System.Collections.Generic;  
  2.   
  3. namespace EF.Core.Data  
  4. {  
  5.     public class Student : BaseEntity  
  6.     {  
  7.         public string Name { getset; }  
  8.         public byte Age { getset; }  
  9.         public bool IsCurrent { getset; }  
  10.         public virtual ICollection<Course> Courses { getset; }  
  11.     }  

The Course entity is as in the following code snippet that is defined under the EF.Core Project.

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace EF.Core.Data  
  5. {  
  6.    public class Course : BaseEntity  
  7.     {  
  8.        public string Name { getset; }  
  9.        public Int64 MaximumStrength { getset; }  
  10.        public virtual ICollection<Student> Students { getset; }  
  11.     }  

Both code snippets above have navigation properties that are collections, in other words one entity has another entity collection.

Now creates a class StudentMap class in the EF.Data project to implement a Fluent API configuration for the Student class.

  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity.ModelConfiguration;  
  3. using EF.Core.Data;  
  4.   
  5. namespace EF.Data.Mapping  
  6. {  
  7.    public class StudentMap : EntityTypeConfiguration<Student>  
  8.     {  
  9.        public StudentMap()  
  10.        {  
  11.            //key  
  12.            HasKey(t => t.ID);  
  13.   
  14.            //property  
  15.            Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  16.            Property(t => t.Name);  
  17.            Property(t => t.Age);  
  18.            Property(t => t.IsCurrent);  
  19.            Property(t => t.AddedDate).IsRequired();  
  20.            Property(t => t.ModifiedDate).IsRequired();  
  21.            Property(t => t.IP);  
  22.   
  23.            //table  
  24.            ToTable("Students");  
  25.   
  26.            //relationship  
  27.            HasMany(t => t.Courses).WithMany(c => c.Students)  
  28.                                 .Map(t => t.ToTable("StudentCourse")  
  29.                                     .MapLeftKey("StudentId")  
  30.                                     .MapRightKey("CourseId"));  
  31.        }  
  32.     }  

The code snippet above shows that one student can join many courses and each course can have many students. As you know, to implement Many-to-Many relationships we need a third table named StudentCourse. The MapLeftKey() and MapRightKey() methods define the key's name in the third table otherwise the key name is automatically created with classname_Id. The Left key or first key will be that in which we are defining the relationship.

Now create a class, the CourseMap class, in the EF.Data project to implement the Fluent API configuration for the Course class.

  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity.ModelConfiguration;  
  3. using EF.Core.Data;  
  4.   
  5. namespace EF.Data.Mapping  
  6. {  
  7.    public class CourseMap :EntityTypeConfiguration<Course>  
  8.     {  
  9.        public CourseMap()  
  10.        {  
  11.            //property  
  12.            Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  13.            Property(t => t.Name);  
  14.            Property(t => t.MaximumStrength);             
  15.            Property(t => t.AddedDate).IsRequired();  
  16.            Property(t => t.ModifiedDate).IsRequired();  
  17.            Property(t => t.IP);  
  18.   
  19.            //table  
  20.            ToTable("Courses");            
  21.        }  
  22.     }  

No we create another unit test class in the EF.UnitTest Project to test the code above. Let’s see the test method that inserts data in all three tables.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using EF.Core.Data;  
  5. using EF.Data;  
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  7.   
  8. namespace EF.UnitTest  
  9. {  
  10.     [TestClass]  
  11.     public class StudentTest  
  12.     {  
  13.         [TestMethod]  
  14.         public void StudentCourseTest()  
  15.         {  
  16.             Database.SetInitializer<EFDbContext>(new CreateDatabaseIfNotExists<EFDbContext>());  
  17.             using (var context = new EFDbContext())  
  18.             {  
  19.                 context.Database.Create();  
  20.                 Student student = new Student  
  21.                 {  
  22.                     Name = "Sandeep",  
  23.                     Age = 25,  
  24.                     IsCurrent = true,  
  25.                     AddedDate = DateTime.Now,  
  26.                     ModifiedDate = DateTime.Now,  
  27.                     IP = "1.1.1.1",  
  28.                     Courses = new List<Course>{  
  29.                         new Course  
  30.                         {  
  31.                             Name = "Asp.Net",  
  32.                             MaximumStrength = 12,  
  33.                             AddedDate = DateTime.Now,  
  34.                             ModifiedDate = DateTime.Now,  
  35.                             IP = "1.1.1.1"  
  36.                         },  
  37.                          new Course  
  38.                         {  
  39.                             Name = "SignalR",  
  40.                             MaximumStrength = 12,  
  41.                             AddedDate = DateTime.Now,  
  42.                             ModifiedDate = DateTime.Now,  
  43.                             IP = "1.1.1.1"  
  44.                         }  
  45.                     }  
  46.                 };  
  47.                 Course course = new Course  
  48.                {  
  49.                    Name = "Web API",  
  50.                    MaximumStrength = 12,  
  51.                    AddedDate = DateTime.Now,  
  52.                    ModifiedDate = DateTime.Now,  
  53.                    IP = "1.1.1.1",  
  54.                    Students = new List<Student>{  
  55.                         new Student  
  56.                         {  
  57.                             Name = "Raviendra",  
  58.                             Age = 25,  
  59.                             IsCurrent = true,  
  60.                             AddedDate = DateTime.Now,  
  61.                             ModifiedDate = DateTime.Now,  
  62.                             IP = "1.1.1.1",  
  63.                         },  
  64.                          new Student  
  65.                         {  
  66.                           Name = "Pradeep",  
  67.                         Age = 25,  
  68.                         IsCurrent = true,  
  69.                         AddedDate = DateTime.Now,  
  70.                         ModifiedDate = DateTime.Now,  
  71.                         IP = "1.1.1.1",  
  72.                         }  
  73.                     }  
  74.                };  
  75.                 context.Entry(student).State = System.Data.EntityState.Added;  
  76.                 context.Entry(course).State = System.Data.EntityState.Added;  
  77.                 context.SaveChanges();  
  78.             }  
  79.         }  
  80.     }  

Now run the Test method and you get your table in the database with data. Run the select query in the database and get results like.

  1. SELECT [ID],[Name],[Age],[IsCurrent],[AddedDate],[ModifiedDate],[IP] FROM [EFCodeFirst].[dbo].[Students]  
  2. SELECT [ID],[Name],[MaximumStrength],[AddedDate],[ModifiedDate],[IP] FROM [EFCodeFirst].[dbo].[Courses]  
  3. SELECT [StudentId],[CourseId] FROM [EFCodeFirst].[dbo].[StudentCourse] 



Figure 1.7: Data for Students and Courses.

Conclusion

This article introduced relationships in the Entity Framework Code First approach using the Fluent API. I didn’t use database migration here; that is why you need to delete your database before running any test method of the unit. If you have any doubt, post as a comment.

Up Next
    Ebook Download
    View all
    Learn
    View all