CRUD using Code First Approach of Entity Framework (EF)

Rajnilari2015
Posted by in Entity Framework category on for Beginner level | Points: 250 | Views : 1297 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article we will use the Code First Approach of EF to demonstrate the CRUD operation. A Console Application will act as the Client Application.


 Download source code for CRUD using Code First Approach of Entity Framework (EF)

Introduction

Entity Framework (EF) is an Object Relational Mapper (ORM) that helps to work with relational data using domain-specific objects. For accessing the data, EF provides three approaches viz

  1. Code First Approach
  2. Database First Approach
  3. Model First Approach

In this article we will use the Code First Approach of EF to demonstrate the CRUD operation. A Console Application will act as the Client Application.

Environment Setup

Let us first fire up a console application in Visual Studio and choose "Console Application".

Go to the project References > Manage NuGet Packages and install EntityFramework.

We are using EntityFramework 6.1.3 version.

Create a domain class

Once done, then add a class file. Name it say Author.cs with the below properties

using System;
using System.ComponentModel.DataAnnotations;

namespace CRUD_CodeFirst
{
    public class Author
    {
        [Key]
        public int AuthorID { get; set; }
        public string AuthorName { get; set; }
        public string BookTitle { get; set; }
        public DateTime PublicationDate { get; set; }
    }
}

This is our domain class.

Create a Context class

Code-First approach also requires Context class which should be derived from DbContext. A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

So let's go ahead and add a class file. Name it say AuthorContext.cs as under

using System.Data.Entity;

namespace CRUD_CodeFirst
{
    public class AuthorContext : DbContext
    {
        public AuthorContext() : base("dbConnectionString")
        {
            Database.SetInitializer<AuthorContext>(new CreateDatabaseIfNotExists<AuthorContext>());
        }
        public DbSet<Author> Authors { get; set; }
    }
}

Make an entry of the connection string in the app.config

Open app.config file and make an entry for the connection string as udner

<connectionStrings>
    <add name="dbConnectionString" connectionString="Data Source=yourdatasource;Initial Catalog=AuthorDB;User ID=youdbuserid;Password=yourdbpassword;pooling=false;MultipleActiveResultSets=True;pooling=false;" providerName="System.Data.SqlClient" />
  </connectionStrings>

The full config file is presented below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="dbConnectionString" connectionString="Data Source=yourdatasource;Initial Catalog=AuthorDB;User ID=youdbuserid;Password=yourdbpassword;pooling=false;MultipleActiveResultSets=True;pooling=false;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">-->
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

We are almost done. Now we need to perform the CRUD operation

Write the CRUD code in the Program.cs file

Let us first write the code for inserting the records

using System;

namespace CRUD_CodeFirst
{
    class Program
    {
        static void Main(string[] args)
        {           

            //Insert into Author table 
            using (var context = new AuthorContext())
            {
                for (int i = 0; i < 10; i++)
                {
                    Author objAuthor = new Author() { AuthorName = "Author" + i, BookTitle = "Book" + i, PublicationDate = DateTime.Now.AddMonths(i) };

                    context.Authors.Add(objAuthor);
                    context.SaveChanges();
                }
            }
        }
    }
}

The code above shows how to create and add new Author(s) to AuthorDB database.Earlier we have declared the collection of Authors as a property in the AuthorContext class.

public DbSet<Author> Authors { get; set; }

We are adding Author objects to that collection and then calling the SaveChanges method to save the changes to database.

The result is as under

Next we will write the code for fetching the records

//select records
using (var context = new AuthorContext())
{
   context
   .Authors
   .ToList()
   .ForEach
   (
     a => Console.WriteLine("AuthorId={0} AuthorName={1} BookTitle={2} PublicationDate={3}", a.AuthorID, a.AuthorName, a.BookTitle, a.PublicationDate.ToString("dd/mm/yyyy"))
   );
}

The result is as under

The next code for updating the record(s)

//Update into Author table 
using (var context = new AuthorContext())
{
    Author objAuthor = new Author() { AuthorID = 5, AuthorName = "RNA Team", BookTitle = "CRUD using Code First Approach", PublicationDate = DateTime.Now };
    context.Authors.Add(objAuthor);
    context.Entry(objAuthor).State = EntityState.Modified;
    context.SaveChanges();
}

For updating the record we need to attach the updated record to the corresponding DBSet property and set the entity state to EntityState.Modified and finally call the SaveChanges() method to save the changes to the database.

The result is as under

The last code for deletion of the record(s)

//Delete an Author
using (var context = new AuthorContext())
{
    int authorID = 7;
    var author = context.Authors.Find(authorID); //specify the AuthodId
    context.Authors.Remove(author); //removes the entity from the Authors Entities/Collections
    context.SaveChanges();
}

First we need to find the Author entity and then remove that from the collection by using the Remove method. Lastly, apply the SaveChanges

The result is as under

As can be figure out that AuthorId=7 has been deleted.

The complete code is presented below

using System;
using System.Data.Entity;
using System.Linq;

namespace CRUD_CodeFirst
{
    class Program
    {
        static void Main(string[] args)
        {

            //Insert into Author table 
            using (var context = new AuthorContext())
            {
                for (int i = 0; i < 10; i++)
                {
                    Author objAuthor = new Author() { AuthorName = "Author" + i, BookTitle = "Book" + i, PublicationDate = DateTime.Now.AddMonths(i) };
                    context.Authors.Add(objAuthor);
                    context.SaveChanges();
                }
            }

            //Select Author records
            using (var context = new AuthorContext())
            {
                context
                    .Authors
                    .ToList()
                    .ForEach
                    (
                        a => Console.WriteLine("AuthorId={0} AuthorName={1} BookTitle={2} PublicationDate={3}", a.AuthorID, a.AuthorName, a.BookTitle, a.PublicationDate.ToString("dd/mm/yyyy"))
                    );
            }

            //Update into Author table 
            using (var context = new AuthorContext())
            {
                Author objAuthor = new Author() { AuthorID = 5, AuthorName = "RNA Team", BookTitle = "CRUD using Code First Approach", PublicationDate = DateTime.Now };
                context.Authors.Add(objAuthor);
                context.Entry(objAuthor).State = EntityState.Modified;
                context.SaveChanges();
            }


            //Delete an Author
            using (var context = new AuthorContext())
            {
                int authorID = 7;
                var author = context.Authors.Find(authorID); //specify the AuthodId
                context.Authors.Remove(author); //removes the entity from the Authors Entities/Collections
                context.SaveChanges();
            }

            Console.ReadKey();

        }
    }
}

Conclusion

So in this article we have learnt how to perform the CRUD operation using the Code First Approach of EF. Hope it was useful. Thanks for reading. Zipped file attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Bhuvanesh6 on: 7/25/2016 | Points: 25
Simple & Clear to understand.

Login to post response

Comment using Facebook(Author doesn't get notification)