Code First Entity Framework with ASP

 

Entity framework is a relationship mapper framework which was introduced by Microsoft to automate all the database related activities. Entity framework became very popular among developers after it’s release because prior to .NET 3.5, developers used ADO.NET to connect to the database, execute queries on it to fetch a dataset and then perform the business rules on the data set. The whole process was very prone to errors and was actually a really tedious process.

Entity framework directly works with database with domain specific classes and bridges the gap for faster execution, better abstraction and lesser lines of code.

How to start with Code First Entity Framework?

Before we begin working with Entity Framework, we need to know which type you want to work with. There are three types of Entity Framework

  • Database First
  • Model First
  • Code First

Today, we are going to go ahead with Code First Entity Framework. It is a domain driven design, which basically means that we design our models according to our business rules. And EF creates the database for those models. EF can work in three ways to create a database for you – CreateDatabaseIfNotExists, DropCreateDatabaseIfModelChanges, DropCreateDatabaseAlways.

To install EF onto a solution/project, go to Tools -> NuGet Package Manager -> Package Manager Console. And in the window that opens up, type

Install-Package EntityFramework

The above will install the latest Entity Framework for that project. Now, create a class named MyDatabaseContext and extend the DbContext class in your project. This class will help us in implementing the EF functionalities. Now, create a constructor for MyDatabaseContext like below

  1. using System.Data.Entity;
  2. using System.Data.Entity.ModelConfiguration.Conventions;
  3. using Example.Models;
  4. namespace Example.Context
  5. {
  6. public class MyDatabaseContext : DbContext
  7. {
  8. public MyDatabaseContext() : base(“MyDatabase”)
  9. { }
  10. }
  11. }

And add a connection string in your web.config with the same name as the parameter in the constructor above like

  1. <connectionStrings>
  2. <add name=”MyDatabase” connectionString=”Server=.\SQLEXPRESS;Initial Catalog=Student;” providerName=”System.Data.SqlClient” />
  3. </connectionStrings>

Now create a model and add some properties that you would want in your database table. To make a property the key of the table, add [Key] attribute to it, which would define it as the primary key of the table.

  1. usingSystem;
  2. usingCollections.Generic;
  3. usingComponentModel.DataAnnotations;
  4. usingLinq;
  5. usingText;
  6. usingThreading.Tasks;
  7. namespaceModels
  8. {
  9. publicclass Student
  10. {
  11. [Key]
  12. publicint ID { getset; }
  13. publicstring Name { getset; }
  14. }
  15. }

Now add the below line to your MyDatabaseContext

public DbSet<Student> Students { getset; }

Now, we’ll enable the code-first migrations on the project and add our first migration. After adding the migration, we’ll create the database and a Student table for the Student model. To do so, open the Package Manager Console and be sure to select the project on which you installed the Entity Framework before.

Run Enable-Migrations

This command above will enable migration on your project

Run Add-Migration YourMigrationName

This will Scaffold a migration script for any new or pending model changes. You can choose any name instead of YourMigrationName

Run Update-Database

This will apply any pending migrations to your database and create/modify the database

Now, you are all set to run your first Code-First EF application. Rebuild your solution and add a controller in the same manner as below.

And on the next screen

If you followed the steps correctly, you will be able to perform CRUD operations on your students and you will see a full-fledged database on your SQL Server. Now, you can execute any number of complex queries on your database using LINQ and perform your business rules accordingly.

Why choose Code First Entity Framework Code First approach?

Now that we have covered the basic example of creating a web application using Code First approach, you might be wondering why one would want to take that approach? Well, there are a number of reasons why Code First is a favorite of developers over others

  • Using Code first approach, one can forget about the tedious process of deployment. The one-click publish option gives you the freedom you deserve. While configuring a publish profile, you have the option to Execute Code First Migrations which will publish all the changes that you did on your local machine directly on your server. And that too, with a production connection string that will be replaced with your local connection string while the solution is being published automatically.

  • There are some projects which require a number of developers for the sake of the size of the project. And that is where Code First makes it easy for developers to version their database changes, which are very tedious and critical. Whenever you change your models and add a migration, it is added to a Migrations folder where you can track all your database related changes.
  • You can change the database schema fairly easily and Code First is recommended when the development of models is done by developers themselves.

So, that’s pretty much it about the Code First approach with Entity Framework. Next time, we’ll be up with some nifty LINQ hacks to avoid longer execution times and better performance.

Shushant Tyagi