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

Creating an ASP.NET Web API using the Entity Framework Code First approach and the Repository pattern

In this article, we will learn how to create an ASP.NET Web API using the Repository pattern and the Entity Framework code first approach. Essentially you’ll learn how to:

  1. Create a core project which will contain entity and the repository interface;
  2. Create an Infrastructure project which will contain database operations code using the Entity Framework code first approach;
  3. Create a Web API to perform CRUD operations on the entity;
  4. Consume the Web API in a jQuery application and render the data in the Ignite UI Chart.

What is a Repository pattern?

Let us first understand why we need a Repository pattern. If you do not follow a Repository pattern and directly use the data then the following problems may arise-

  • Duplicate code
  • Difficulty implementing any data related logic or policies such that caching
  • Difficulty in unit testing the business logic without having the data access layer
  • Tightly coupled business logic and database access logic

By implementing a repository pattern we can avoid the above problems and get the following advantages:

Business logic can be unit tested without data access logic

  • Database access code can be reused
  • Database access code is centrally managed so easy to implement any database access policies such that caching
  • Easy to implement domain logics
  • Domain entities or business entities are strongly typed with the annotations.

Now that we’ve listed how great they are, let’s go ahead and start implanting a repository pattern in the ASP.NET Web API.

Create the Core project

In the core project you should keep the entities and the repository interfaces. In this example we are going to work with the City entity. So let us create a class City as shown in the listing below:

Read the full article on the Infragistics blog

Video : One to one relationship between entities in Entity Framework Code First

Container.cs



namespace EFCodeFirstDemo.EFLib
{
   public class Container
    {
        public int ID { get; set; }
        public string ContainerName { get; set; }

        public virtual  Product product { get; set; }

    }
}


Product.cs


using System.ComponentModel.DataAnnotations;

namespace EFCodeFirstDemo.EFLib
{
   public class Product
    {
   
      // [ForeignKey("Container")]
        public int ID { get; set; }
        public string  ProductName { get; set; }

        public double  ProductPrice { get; set; }

        [Required]
        public virtual Container container { get; set; }
    }
}



EFContext.cs


using System.Data.Entity;

namespace EFCodeFirstDemo.EFLib
{
   public class EFContext : DbContext
    {
       public EFContext()
       {
           Database.SetInitializer<EFContext>(new DropCreateDatabaseIfModelChanges<EFContext>());
       }

       public DbSet<Product> Products { get; set; }
       public DbSet<Container> Containers { get; set; }
    }
}



Getting started with Code First Approach and Entity Framework Migrations Commands

For better understanding on Entity Framework, I recommend you to read EF Series by Anders Abel on his blog here . I learnt lot from his post about Entity Framework. You may want to follow Julie Lerman for better learning on ADO.NET Entity Framework.

In this post we will walk through basics of Entity Framework migration commands and learn about Code First Approach. Entity Framework allows you to create database from plain classes. You can model your domain into classes and subsequently database can be created or updated from the model using Entity Framework.

We model domain into classes and database gets created form model classes is known as Code First Approach. Here you can create database from plain old classes. Model classes does not have to extend any base class etc. The other two approaches are,

  1. Model First Approach
  2. Database First approach

Code First Approach in Entity Framework reduce task of modelling database on designer and working with XML etc.

Let us start rolling, suppose we need to model School database. For this we have created two POCO classes as below.


Public class School
    {
        public int Id { get; private set; }
        public string Name { get; set; }

        public Icollection<Student> Students { get; set; }

    }

    public class Student
    {
        public int Id { get; private set; }
        public string Name { get; set; }
        public string  Grade { get; set; }
    }


School and Student classes are representing School and Students real time entities respectively. Next we need to create Context class. This class must inherit DbContext class.


Public class Context : DbContext
    {
      public Context() :base()
        {

        }
        public DbSet<Student> Students { get; set; }
        public DbSet<School> Schools { get; set; }
    }


Regardless what kind of application you are working with and following Code First approach, you need to add reference of EntityFramework. You can use NuGet manager to install EntityFramework library in project you are working.

image

When you execute code, surprisingly you will find database has been created. You may wonder that where Context database (we created class Context which is inheriting DbContext class) has been created? Let us go back to context class, we have not provided any connection string in constructor. In this case database would get created in local SQL Express comes with Visual Studio. Alternatively connection string name can be provided in constructor to create database on a particular database server. Connection string can reside in configuration file. You can launch Server Explorer to view created database. Let us go ahead and examine schema of created table,

Student table is created as below,

image

And School table being created as below,

image

EF is intelligent enough to construct primary key on the column with name Id. If you don’t have Id column then EF will search for column with *Id and construct that column as primary key. For example if there is a property EmployeeId in model class then EF will construct column EmployeeId as primary key.

Other thing you may notice that for string properties EF is creating columns with type nvarchar(MAX). You may not want this and have control on size of the columns in database. This is allowed in EF using data annotations. Let’s go ahead and modify POCO classes with data annotation.


Public class School
    {
        public int Id { get; private set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }

        public Icollection<Student> Students { get; set; }

    }

    public class Student
    {
        public int Id { get; private set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        [Required]
        [StringLength(10)]
        public string  Grade { get; set; }
    }


We have put data validation annotations like Required (in db null not allowed) and StringLength. Other data validation annotations are MaxLength and MinLength.

Let’s go ahead and run again to recreate or update database schema. On running application I got following exception. Poor me,

image

EF is throwing very clear error message. We can break error in message in two parts,

  1. Model backing Context has changed
  2. It has changed since database has created

It is suggesting us to consider Code First Migration. So let’s learn Code First Migration. Before we go ahead and explore various migration techniques, let’s have a look on Database initialization strategies. There are four database initialization strategies,

  1. CreateDatabaseIfNotExist
  2. DropCreateDatabaseIfModelChanges
  3. DropCreateDatabaseAlways
  4. Cutsom DB Initalizer

All options are self-explanatory. One option is to use DropCreateDatabaseIfModelChanges database initializer to get rid of above exception. Let’s go ahead and modify Context class by adding database initializer in constructor,


public class Context : DbContext
    {
      public Context() :base()
        {

            Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>());

        }
        public DbSet<Student> Students { get; set; }
        public DbSet<School> Schools { get; set; }
    } 


Okay so we did not get any exception and database schema has been updated as well. You may notice Name column has been updated with length 50 and Nulls are not allowed.

image

All good? Not really because we have lost all the data. Since in database initializer we have used option to drop database and create again if model changed. I am sure you don’t like this option and must be looking for some better options.

Other option is to Enable Migrations. You can enable migration by EF command. You can run EF command from Package Manager Console. Enable Migrations run command

PM> Enable-Migrations

image

I have run command to enable automatic migration. Let’s go back to solution explorer, you will find a Migration folder is being added with a class Configuration.cs . This class got a seed method. Configuration class will look like below,


internal sealed class Configuration : DbMigrationsConfiguration<SchoolDbApplication.Context>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = “SchoolDbApplication.Context”;
        }

        protected override void Seed(SchoolDbApplication.Context context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = “Andrew Peters” },
            //      new Person { FullName = “Brice Lambson” },
            //      new Person { FullName = “Rowan Miller” }
            //    );
            //
        }
    }


As you see that,

  1. AutomaticMigrationEnabled is set to true
  2. There is Seed method which will get executed after migrating to the latest version. So if you want to have some default data after migration, you will write code in Seed method.

Let us consider another scenario that we want to add one more column in Student table and for that we need to add a property in Student class. Modified Student class will look like below,


public class Student
    {
        public int Id { get; private set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        [Required]
        [StringLength(10)]
        public string  Grade { get; set; }
        [Required]
        public int Age { get; set; }
    }


I have added Age property with basic data annotation [Required]. Previously when we tried modifying class and later database we lost all the data. This time we don’t want to repeat the mistake. So after modifying model class, add a migration with a name. Let’s run a command and give a name Student_Age to newly added migration. You are allowed to give any name of your choice.

PM> Add-Migration Student_Age

image

Further if required you can change Model and include in the same migration by running the same command. Let us go ahead and explore solution explorer again. In solution explorer inside Migrations folder you will find somenumber_Student_Age.cs file. This class contains information about this particular migration. Remember that we gave name of the migration as Student_Age.

Namespace SchoolDbApplication.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Student_Age : DbMigration
    {
        public override void Up()
        {
            AddColumn(“dbo.Students”, “Age”, c => c.Int(nullable: false));
        }
        
        public override void Down()
        {
            DropColumn(“dbo.Students”, “Age”);
        }
    }
}


There are two methods inside this class Up and Down method. In Up method a column being added to Students table whereas in Down method column is dropped. Don’t forget to run Update-database command to update model changes in database.

PM> update-database –verbose

image

This time you will find database has been updated and age column is added to Students table with no loss of data.

For complete reference of EF Migrations commands you may want to refer here

Summary

In this post we learnt Code First approach in ADO.NET Entity Framework and some of the EF commands. I left you reference to learn further on same subject also. I hope after learning this post you should able to understand what is going around various EF commands and don’t accidently delete data while updating the schema. In further posts I will talk about Custom DB Initalizer and other important bits of Entity Framework.

Happy Coding.

Reviewing Programming Entity Framework : Code First by Julie Lerman and Rowan Miller

image

Title: Programming Entity Framework: Code First

Number of Pages < 200

Price: $9.99 Kindle Edition

      $21.59 Paperback

Buy here

I got an opportunity to get a copy of book Programming Entity Framework: Code First from well-known author, speaker and an authority on Entity Framework Julie Lerman . I was very excited to get book directly from the author. I got amazed seeing how skillfully and with dexterity both of the authors has written such an important and depth topic in less than 200 pages. Book contains all together 8 chapters and If you are developer working on database centric applications then this book is for you. This book focuses on Code First approach of architecting the application. While you flip through the pages of the books, you will experience the authority of Julie Lerman on the subject.

Before I go ahead and write my experience on this this awesome book, let me give a try to make you understand what is Code First?

Most popular way of architecting an application is to design database first. First you model the requirement into database and then using different API like ADO.Net or ORM like LINQ to SQL Class, NHibernate etc. work with the database. This approach of architecting an application is called as Database First Approach

clip_image002

In .NET 3.5 Microsoft came up with ADO.Net Entity Framework, It was helping developers to create conceptual model.

  • It was creating Conceptual model into XML File.
  • Extension of XML file is EDMX.
  • XML file can be seen in designer where developers can edit the design on conceptual model.

ADO.Net Entity Framework was working on concepts of Database first approach where conceptual model gets created on existing database.

One of the most popular ways of architecting your application is to have Model First. You may have mapped database requirement in a XML file and create database from the XML file. This approach of architecting database is called Model First Approach.

image

In Model first approach you can start working on project without having a database. You can design the conceptual model using Visual Studio designer and later database can be created from this conceptual model.

In .NET 4.0 and Visual Studio 2010, Microsoft came up with new version of ADO.Net Entity Framework version 4.0 and it was supporting developers to architect their application as Model First approach.

Regardless of the approach you use in your application automatically lot of codes get created as classes and you work with the classes. Here comes a third way of creating Database and that is Code First approach. In this you model your requirement in plain classes and then databases gets created from these classes. Developers first create Domain Classes and then later database gets created from these domain classes.

image

In your application POCO classes are model and they are used to create the database. This approach of architecting an application is called “CODE FIRST”.

Now if you have a basic understanding of Code first approach after reading above paragraph then you should be thanking Julie Lerman rather me because my understating was based on first two paragraph of first chapter of book titled Programming Entity Framework: CODE FIRST

Table Of Contents

image

By seeing table of contents you must have got an idea that how useful this book would be if you are a developer working on Database centric applications.

About Authors

image

Julia Lerman is the leading independent authority on the Entity Framework and has been using and teaching the technology since its inception in 2006. She is the author of the highly acclaimed book, Programming Entity Framework, 1st and 2nd editions and is well known in the .NET community as a Microsoft MVP, ASPInsider, and INETA Speaker. Julia is a frequent presenter at technical conferences around the world and writes articles for many well-known technical publications including the Data Points column in MSDN Magazine. Julia blogs at http://thedatafarm.com/blog

Rowan Miller is Program Manager in ADO.Net Entity Framework team at Microsoft.

Conclusion

I strongly suggest to you to read this book and take your expertise to next level. All 8 chapters’ of this book will help you to have a better understating on the Code First approach and codes samples will help you to understand better way of modeling your database from the code.