Step By Step Implement Database First Approach in MVC

Database First, as name suggest we have a database table first and we are going to use it and create our Model. For that, first we have to create a database table, let’s create a Country table by running the following script.

  
  1. /****** Object:  Table [dbo].[Country]    Script Date: 25-12-2015 10:00:58 ******/  
  2. SET ANSI_NULLS ON  
  3. GO  
  4.   
  5. SET QUOTED_IDENTIFIER ON  
  6. GO  
  7.   
  8. CREATE TABLE [dbo].[Country](  
  9.     [CountryId] [int] IDENTITY(1,1) NOT NULL,  
  10.     [CountryName] [nvarchar](50) NULL,  
  11.  CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED   
  12. (  
  13.     [CountryId] ASC  
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  15. ON [PRIMARY]  
  16.   
  17. GO  
Next step, create a new project, Select Web, then ASP.NET Web Application and select MVC Template. Click 'Ok'.

 
 
 Next, Add Model, Right click on project and add ADO.NET Entity Data Model.
 
 
Give a Name to your Model.
 
 
Now, Next dialog box ask you to Choose Model Contents, here we will choose 'E F Designer from database' and click 'Next'.
 
 

Next screen, we will complete the database connectivity.

 
 
Save Connection string in Web.Config file.

 
 
Select the table you want to connect from Entity Data Model Wizard, here we will select 'Country' Table. It will Include Namespace 'DemoModel' and after that click 'Finish'. 
 
 
 
It will create 'Model1.edmx' file in our project.

 
Now try to create Controller, by right click on Controllers and selecting Controller,
 
 
Select MVC 5 Controller with views, using Entity Framework,
 
 
Select Model Class 'Country' and Database context class as 'DemoEntities', and it will automatically assign name 'CountriesController', So our Controller name will be CountriesController.
 
 
 
Now if you try to click on 'Ok' it will give you error message because we haven't build our project, so let's build the project and add the CountriesController.
 
 
 
Scaffolding method will automatically create ActionResult in Controller like Create, Delete, Edit, Index and View. Also create Countries folder in View with Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml and Index.cshtml.
 
 
Run the application http://localhost:/Countries, Add country, Edit or Delete Country and check the application.

 
 
 
 
So, its easy to start with database first approach for small or mid size project using database first approach using scaffolding method.
 
Hope you like this article. 


Similar Articles