Create A New Database Using Code First In Entity Framework

Steps to create new database by using code first in Entity framework

Note - I am using Visual Studio 2015 for creating this project.

Step 1 - Create Windows form project

Visual Studio, File menu, New, then click Project .

Select “Window” from templates and select “Window Form application”.

Form application

So it will create Window Form application and I have given its name “CodeFirstDBCreation” during creation.

Step 2 - Add entity frame work into newly created project using NuGet package.

Need entity frame work for using code first for creation of database.

Right Click over project -> Manage Nuget packages -> search EntityFramework

EntityFramework

Now click over “Install” button to install entity frame into selected project.

Install

Now it is installed over project and some references over project.

Added reference 'EntityFramework' to project 'CodeFirstDBCreation'.

Added reference 'EntityFramework.SqlServer' to project 'CodeFirstDBCreation'.

Added reference 'System.ComponentModel.DataAnnotations'.

And add also add tags into app.config file <configSections> and <entityFramework>

Step 3 - Create Model into project

Add model class into project.

Example

  1. public class Company  
  2. {  
  3.     public String CompanyId   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public String Name   
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13. }  
Step 4 - Create Context class into project
  1. public class CodeFirstContext: DbContext   
  2. {  
  3.     public CodeFirst(): base()   
  4.     {  
  5.         Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());  
  6.     }  
  7.   
  8.   
  9. }  
Create “CodeFirstContext” class, which will inherit “DbContext” (DbContext exist inside System.Data.Entity namespace), this derives context class and represents  session with database and helps us to make transactions with database like save the data or fetch the data from database.

Step 5 - Exposed typed DbSet for each classes of model

Now expose each class of model into derived context (CodeFirstContext) by using DbSet<TEntity>. DbSet represents an entity set, which willbe used to perform operations like add, update, delete and read.
  1. class CodeFirstContext: DbContext  
  2. {  
  3.     public CodeFirstContext(): base()   
  4.     {  
  5.         Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());  
  6.     }  
  7.   
  8.     public DbSet < Company > Companies   
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.   
  14. }  
Right now we have only one data model “Company”, so we exposed only it inside context using DbSet, as we start growing our data model classes, so we need to expose more model classes inside this context. As a DbContext we are done here.

Note - We will discuss about base class constructor of DbContext and its use in database creation at the end of these steps.

Step 6 - Create input section

Create input section, it can be anything for input, whether console or win form etc. We have created Win form application so we will create win form.

form

Step 7- Code to add entity into DB by DbSet of context
  1. private void btnAdd_Click(object sender, EventArgs e)  
  2. {  
  3.     // Set values into company model.  
  4.     Company objCompany = new Company();  
  5.     objCompany.CompanyId = txtCompanyId.Text;  
  6.     objCompany.Name = txtCompanyName.Text;  
  7.   
  8.     // Create context object and then save company data.  
  9.     CodeFirstContext objContext = new CodeFirstContext();  
  10.     objContext.Companies.Add(objCompany);  
  11.     objContext.SaveChanges();  
  12.   
  13. }  
In the above code we add property values of model Company, And then create context object, then with help of context object, we get Company DbSet and then with the help of Dbset we performed the “add” operation into database.

So now If at that moment, if we run the application and add company name and Id and save it, so it will create data base and create one table inside it by the name of “Companies” and add one record inside it, on the basis of input entry.

Now a question arises, we didn’t mention any connection string, so how and where will database be created?
  1. If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance.

  2. If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012).

The database is named by the combination of ProjectName.ContextName , in our case that is CodeFirstDBCreation.CodeFirstContext , here CodeFirstDBCreation is our project name and CodeFirstContext is our derived context name.

name

Tables

Tables

Role of Base class constructor of context over Database creation:

Base class constructor has following parameters

  1. No Parameter:
  2. Database name as parameter:
  3. Connection string name as parameter:

No Parameter

  1. class CodeFirstContext: DbContext  
  2. {  
  3.     public CodeFirstContext(): base()   
  4.     {  
  5.         Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());  
  6.     }  
  7.     public DbSet < Company > Companies   
  8.     {  
  9.         get;  
  10.         set;  
  11.     }  
  12.   
  13. }  
In this case it will create data bases on localDb instance and its name will be the combination of Project name and derived context name. In our case it will be “CodeFirstDBCreation.CodeFirstContext”.

Database name as parameter
  1. class CodeFirstContext: DbContext   
  2. {  
  3.     public CodeFirstContext(): base("CompanyDB")   
  4.     {  
  5.         Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());  
  6.     }  
  7.     public DbSet < Company > Companies   
  8.     {  
  9.         get;  
  10.         set;  
  11.     }  
  12.   
  13. }  
In this case it will create data bases on localDb instance and its name will be the name which we pass in base class constructor “CompanyDB”.

CompanyDB

Connection string name as parameter
  1. class CodeFirstContext: DbContext  
  2. {  
  3.     public CodeFirstContext(): base("name=CompanyConnectionString")   
  4.     {  
  5.         Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());  
  6.     }  
  7.     public DbSet < Company > Companies  
  8.     {  
  9.         get;  
  10.         set;  
  11.     }  
  12.   
  13. }  
App.config
  1. <connectionStrings>  
  2.     <add name="CompanyConnectionString" connectionString="Server=TESTServer\SQLEXPRESS; Database=Company; uid=sa;password=1234;" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
So in that case it will create data base on the basis of connection string.

 

create