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”.
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
Now click over “Install” button to install entity frame into selected project.
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
- public class Company
- {
- public String CompanyId
- {
- get;
- set;
- }
- public String Name
- {
- get;
- set;
- }
- }
Step 4 - Create Context class into project
- public class CodeFirstContext: DbContext
- {
- public CodeFirst(): base()
- {
- Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());
- }
-
-
- }
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.
- class CodeFirstContext: DbContext
- {
- public CodeFirstContext(): base()
- {
- Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());
- }
-
- public DbSet < Company > Companies
- {
- get;
- set;
- }
-
- }
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.
Step 7- Code to add entity into DB by DbSet of context
- private void btnAdd_Click(object sender, EventArgs e)
- {
-
- Company objCompany = new Company();
- objCompany.CompanyId = txtCompanyId.Text;
- objCompany.Name = txtCompanyName.Text;
-
-
- CodeFirstContext objContext = new CodeFirstContext();
- objContext.Companies.Add(objCompany);
- objContext.SaveChanges();
-
- }
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?
- 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.
- 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.
Tables
Role of Base class constructor of context over Database creation:
Base class constructor has following parameters
- No Parameter:
- Database name as parameter:
- Connection string name as parameter:
No Parameter
- class CodeFirstContext: DbContext
- {
- public CodeFirstContext(): base()
- {
- Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());
- }
- public DbSet < Company > Companies
- {
- get;
- set;
- }
-
- }
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
- class CodeFirstContext: DbContext
- {
- public CodeFirstContext(): base("CompanyDB")
- {
- Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());
- }
- public DbSet < Company > Companies
- {
- get;
- set;
- }
-
- }
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”.
Connection string name as parameter - class CodeFirstContext: DbContext
- {
- public CodeFirstContext(): base("name=CompanyConnectionString")
- {
- Database.SetInitializer(new DropCreateDatabaseAlways < CodeFirstContext > ());
- }
- public DbSet < Company > Companies
- {
- get;
- set;
- }
-
- }
App.config - <connectionStrings>
- <add name="CompanyConnectionString" connectionString="Server=TESTServer\SQLEXPRESS; Database=Company; uid=sa;password=1234;" providerName="System.Data.SqlClient" />
- </connectionStrings>
So in that case it will create data base on the basis of connection string.