Home > DeveloperSection > Beginner > Code first approach in entity framework

Code first approach in entity framework


ASP.Net ASP.Net 
Ratings:
0 Comment(s)
 1861  View(s)
Rate this:

Code first approach in entity framework

 

In this article describe the concept of code first approach in entity framework in c#. Here we give the simple example of code first approach in entity framework in c#.

The Microsoft Entity Framework is an Object Relational Mapping (ORM) tool that enables you to generate a data access layer from a database automatically. The Entity Framework enables you to avoid the tedious work of building your data access classes by hand. In Code First approach we avoid working with the Visual Designer of Entity Framework. We can say, the EDMX file is excluded from the solution. So now, we have complete control over the context class as well as the entity classes.

Code-First approach allows you to define model classes as per the Domain requirements via POCOs ("plain-old" CLR objects). Hence, you have complete control over the classes being written or Implemented. Code First Migrations allow you to create a new database or to update existing database based on your model classes by using Package Manager Console exist within Visual Studio 2013 or Visual Studio 2012.

Here we understand by the example of code first approach in entity framework and define the steps to add entity framework.

Step 1

Let’s create a console application as EFCodeFirstExample:

Open visual studio-> New-> Project-> Console Application.

Step 2

Install the Entity Framework:

Solution explorer -> Right Click -> Manage Nuget Packages…  or

Install by package manager console by following command: Install-Package EntityFramework -Version 6.1.0

I describe here graphical:

Code first approach in entity framework

 

Step 3

You can search online search or get first entity framework. Here describe in the screen shot.

 Code first approach in entity framework

 

Step 4

In the last accept license acceptance of Entity framework

Code first approach in entity framework

 

Step 4

Once done, you can see from the project references that the reference to “EntityFramework” is added.

Code first approach in entity framework

We can also add the namespace reference to Entity framework.

using System.Data.Entity;

Step 5

Let’s start with coding part. We will create 2 simple classes (POCO) to understand the code first approach namely “Blog” and “Post”. 

Creating the Blog class in the following:

public class Blog

    {

        public int BlogID { getset; }

        public string Name { getset; }

        public virtual List<Post> Posts  { getset; }

    }

 

Creating the Post class in the following:

public class Post

    {

        public int PostID { getset; }

        public string Title { getset; }

        public string Content { getset; }

        public int BlogID { getset; }

        public virtual Blog Blog { getset; }

    }

 

Step 6

We have created the “BlogID” and “PostID” are both the primary keys in the respective table (the tables are created when the application is running).

Virtual properties (virtual List<Post> Posts and virtual Blog Blog) are marked for lazy loading, which means when we try to access them, entity framework will load the associated data. Those are called navigation properties, which means they will create foreign key constraints in the DB.

Here we create the class of Context as BloggerContext that is derived from the DbContext class:

public class BloggerContext : DbContext

    {

        public BloggerContext()

            : base(nameOrConnectionString:"Data Source=MINDSTICK-2\\SQLEXPRESS;Initial Catalog=BloggerContext;Integrated Security=True;")

        {

        }

 

        public DbSet<Blog> Blogs { getset; }

        public DbSet<Post> Posts { getset; }

    }

 

Here we give the connection string in the BloggerContext class and give database name which is not already exist in sql server. DbSet create table Blogs and Posts tables.

 

Step 7

Here we create the main class for run the code which all the created:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Data.Entity;

 

namespace EFCodeFirstExample

{

    public class Program

    {

        static void Main(string[] args)

        {

            using (var db = new BloggerContext())

            {

                // Create and save a new Blog

                Console.WriteLine("Please enter blog name:");

                string blogName = Console.ReadLine();

 

                Blog blog = new Blog();

                blog.BlogID = 1;

                blog.Name = blogName;

                db.Blogs.Add(blog);

                db.SaveChanges();

 

 

                // List all available blogs in the DB

                Console.WriteLine("All blogs in the DB:");

                foreach (var item in db.Blogs.ToList())

                {

                    Console.WriteLine(item.Name);

                }

                Console.ReadLine();

            }

        }

    }

    public class Post

    {

        public int PostID { getset; }

        public string Title { getset; }

        public string Content { getset; }

        public int BlogID { getset; }

        public virtual Blog Blog { getset; }

    }

    public class Blog

    {

        public int BlogID { getset; }

        public string Name { getset; }

        public virtual List<Post> Posts  { getset; }

    }

    public class BloggerContext : DbContext

    {

        public BloggerContext()

            : base(nameOrConnectionString:"Data Source=.\\SQLEXPRESS;Initial Catalog=BloggerContext;Integrated Security=True;")

        {

        }

 

        public DbSet<Blog> Blogs { getset; }

        public DbSet<Post> Posts { getset; }

    }

} 

Run the application:

Code first approach in entity framework

In this output ‘test1’ are first time added and ‘Entity Framework Blog’ second time run then added into database ‘BloggerContext’ in ‘Blogs’ table. The tables are created after run first time program. If you did not want to give the connection string then it will also create database as default EFCodeFirstExample. BloggerContext that means namespace.context_class_name.

Here we show the database in the sql server:

Code first approach in entity framework

If the SQLServer does not installed then its create database visual studio LocalDb or integrated sqlserver.

Step 8

If you any need to change table schema, then in such case, we need to change out classes which in turn update our DB. To do this we have a feature in Entity Framework called Code First Migrations, or Migrations.

Consider the following class:

public class Blog

    {

        public int BlogID { getset; }

        public string Name { getset; }

        public DateTime DateCreated { getset; }

        public virtual List<Post> Posts  { getset; }

    }

 

To update this change in our DB, we need to enable Code First Migrations for our BloggerContext. Open the “Package Manager Console” from the solution and run the command. Enable-Migrations

Code first approach in entity framework

Step 9

This command will add 2 files in the project named “Configuration.cs” (This file contains the settings that Migrations will use for migrating BloggerContext) and “201405271226104_InitialCreate.cs” (it represents the changes that have already been applied to the database).

And run the command in the package manager console for changing the database: ‘Add-Migration AddDateCreated’ that create a file ‘201405271437404_AddDateCreated.cs’.

Code first approach in entity framework

Step 10

Run the ‘Update-Database’ command in Package Manager Console. This command will apply any pending migrations to the database. You can use the ‘–Verbose’ switch when calling Update-Database to see the SQL that is being executed against the database.

Code first approach in entity framework

Here the sql server database update show:

Code first approach in entity framework

I hope in this article we will try to understand the code first approach in entity framework using console application in c#.


Don't want to miss updates? Please click the below button!

Follow MindStick