Creating DataAccess using Entity Framework

In this blog, we will create data access layer using Entity Framwork Code First Approach.We will be using the same data access layer in our coming blogs.

INTRODUCTION:

We have many ORM frameworks available, Entity Framework is one of the available framework.

So what is ORM (Object Reational Mapping) is a programming technique to convert data between incompatible systems.What is incompatible systems, in this case SQL server and C#, both don’t understand each others language, to make them understand each other we use ORM.

Entity Framerwork helps .net developer write code in C# language, which can be converted to SQL. Entity Framework can be downloaded using NuGet Package Manager. The current version availabe is EF 7.0, which is part of .Net Core. In this blog we will be using EF 6.0

PREREQUISITE:

We will be using be using below given IDE and Frameworks in this blog.

  1. VS 2015
  2. Entity Framework 6.0
  3. Web API 2.0
  4. Class Library Project

We will create a WebApi project and consume the DAL layer directly in our API controllers to see it working. So let’s get’s started and create our project.

  1. Create a project Go to File->New->Project name it as StudentApp and click OK. Choose ASP.NET Web Application.Project.JPG
  2. On Next page create MVC from templates, an select Web API from “Add folders and core references for”, MVC will be select by default, click OK to wait for some time, your project will be loaded.Template.JPG
  3. Now once our project is loaded, let’s see what are the thing we need to ma ke it work, as informed we will create a different project to create our DataAccessLayer.
  4. Leave your project as it is and a new project , right click on solution and Add->New Project and choose Class Library, name it as StudentApp.DAL and click ok.
  5. Let’s add Enity Framework as reference to our poject, we will use NuGet so right click on this recently created project and click Manage NuGet Packages and goto Browse tab and search for EntityFramework and install, it will ask to accept, click accept and references will be added.
  6. In Entity Framework we create conext classes which connects to your database, there are 2 options, we can use a single context class and all Models or We can create a each context for every Models availabe.
  7. For database we will be using localDb, if you open your web.config file from studentApp, we will find a DefaultConnection as connectionString, we will change the database name and change it to StudentDataBase.
  8. Now we need one more project for our Models, let’s add a new ClassLibrary project and name it as StudentApp.ModelModels.JPG
  9. Project will be loaded with Class1.cs , let’s rename the class and change it to Student, it will ask whether, you want to rename all refernces say yes.
  10. Now add few properties to our class, we will see the advantags of entity framework as well. 
    namespace StudentApp.Model
    {
        public class Student
        {
            public int StudentID { get; set; }
            public string FristName { get; set; }
            public string LastName { get; set; }
            public DateTime DateOfBirth { get; set; }
            public DateTime CreatedDate { get; set; }
            public DateTime? ModeifiedDate { get; set; }
        }
    }
    
    
  11. Done with our model class, now build our model project and add reference of this project to our DAL. To add just right click on our DAL project Add-> reference, a box will open from left side choose Project. It will show us 2 option choose StdentApp.Model and click ok.Reference
  12. In our DAL project rename the class1.cs file to StudentContext.cs. So if you are thinking what context class does, it is the model which will talk to our database and help us retrieve the data from DB, let DB know which are the table DB needs to create, with which properties and which database to target.
  13. To create out StudentContext we need to inherit DbContext class, our default constructor will have parameter which will be connectionString Name from our config class. Let’s see the code below.
    namespace StudentApp.DAL
    {
        public class StudentContext : DbContext
        {
            public StudentContext() : base("DefaultConnection")
            {
    
            }
    
            public DbSet<Student> Student { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
            }
        }
    }
    
    
  14. Line number 5 has the default constructor which will initialize our database, the parameter passed is same as our connectionString Name.
  15. Line number 10 has the property as Student, DbSet<> tell the database that we need to create a table with name as Student in our database. and onModelCreting() method let’s us modify properties to table before table is created in DB.
  16. Our context is ready, but to perform operations over our database we need to write our methods, so let’s create a DataStore, this is nothing but a class which will use our StudentContext to perform operation on our DB.
  17. Add a new class in our DAL project and name it as StudentDataStore, we will write 3 methods to GetStudentList(), AddStudent() and UpdateStudent().
  18. Let’s do it by one by one, this will be simple implementation, below is code 
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using StudentApp.Model;
    using System.Data.Entity;
    
    namespace StudentApp.DAL
    {
        public class StudentDataStore
        {
            private StudentContext _context = new StudentContext();
    
            public async Task<List<Student>> GetStudentList()
            {
                return await _context.Student.ToListAsync();
            }
    
            public async Task<bool> AddStudent(Student student)
            {
                student.CreatedDate = DateTime.Now;
                _context.Student.Add(student);
                int x = await _context.SaveChangesAsync();
                return x == 0 ? false : true;
            }
    
            public async Task<bool> UpdateStudent(Student student)
            {
                _context.Entry(student).State = EntityState.Modified;
                student.ModeifiedDate = DateTime.Now;
                int x = await _context.SaveChangesAsync();
                return x == 0 ? false : true;
            }
    
        }
    }
    
    .
  19. We have all 3 methods as async, if you notice Add and Update methods both are using SaveChangesAsync(), this is similar  to our commit is sql, the changes will b be saved to database post this command is fired.
  20. Build the project to check if it is working. Great our build is successful, let’s expose our DAL layer using API.
  21. Add reference of Student.Model and StudentApp.DAL to StudentApp.To add reference right click on Student solution and Add->Reference and select solutions, select both StudentApp.Model and DAL project and click OK.
  22. Now let’s add an API, to Right click on Controller Folder and click Add->Controller, from next screen select Web API 2 Controller – Empty.API
  23. Name the controller as student, we will be calling the same 3 methods in this API.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Web.Http;
    using StudentApp.Model;
    using StudentApp.DAL;
    
    namespace StudentApp.Controllers
    {
        public class StudentController : ApiController
        {
            private StudentDataStore _store = new StudentDataStore();
            public async Task<List<Student>> Get()
            {
                return await _store.GetStudentList();
            }
    
            public async Task<bool> Post(Student student)
            {
                return await _store.AddStudent(student);
            }
    
            public async Task<bool> Put(Student student)
            {
                return await _store.UpdateStudent(student);
            }
    
        }
    }
    
  24. Now build the Student project and press F5. once project is built and page is loaded append /Api/Student/Get.we will get below screenGetAPI
  25. Now we will add a new student using Advanced Rest Client, you can use chrome store to add this App.
  26. In host enter http://localhost:7565/Api/Student/Post and in payload provide {FristName : “Santosh”,LastName: “Yadav”,DateOfBirth: “11/13/1986”}. Below is the request and response.                     Request Response
  27. Now you can call get again and check.GetResult
  28. You can do the same for Put method and see the result.

 

CONCLUSION:

So we have knowledge of how we can create a simple DAL layer using Entity Framework Code First. Unlike old approach we have not created any Database manually, no tables and no scripts, it simplifies the whole process.

Also we used N-Tier architecture in creating this application. In Next blog we will see how entity framework can be used with Repository Pattern.

Keep reading my blog for more topics, you can write to me on santosh.yadav198613@gmail.com in case you need any assistance.

You can download the code from https://github.com/santoshyadav198613/EntityFramework

12 Comments


    1. Thanks vikram, your blogs are also good, will read them for sure. I have also subscribe it.

      Reply

  1. I need to to thank you for this very good read!!

    I absolutely loved every little bit of it. I have you book marked to check out new stuff you http://yahoo.org/

    Reply

  2. I’m amazed, I must say. Seldom do I come across a blog
    that’s equally educative and engaging, and without a doubt,
    you have hit the nail on the head. The problem is
    something not enough people are speaking intelligently about.
    I’m very happy I came across this in my hunt for something concerning this.

    Reply

  3. Its like you read my mind! You appear to know
    a lot about this, like you wrote the book in it or something.
    I think that you can do with a few pics to drive the message home a little bit, but other than that, this is excellent blog.
    A great read. I’ll definitely be back.

    Reply

  4. I’m really impressed together with your writing talents as
    neatly as with the structure for your blog. Is this a paid theme or did you customize it your self?
    Anyway keep up the nice quality writing, it is rare to see a great blog
    like this one these days..

    Reply

  5. Simply deire to saу үouг article is as surprising. TҺᥱ clarity iin үour post iѕ just cool and i cߋuld assume ʏߋu’re
    an expert ⲟn thiѕ subject. Fіne with yoᥙr permissioon ɑllow me
    tо grab your feed to keep up tօ date wіth forthcoming post.

    Thanks a million аnd please continue the gratifying woгk.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *