Entity Framework (2), With .Net MVC, Database-First

After I wrote several articles on this site, I found out it seemed almost for every article, I needed to set up a sample application associated with an entity framework if accessing the database. And, every time, I needed to rewrite the setup process from scratch in order for a new reader to follow along easily. Even for introducing a very simple concept, such as Caching, I needed to spend 80% of the time setting up the sample app, and only 20%  on introducing the Caching concept itself.

Therefore, I think it is better to write a basic model such as entity framework sample for various approaches, and then I can reuse them when needed. I made a list of the series of articles below, I will write them one by one, while the Entity framework overview and concept will be covered in the article (0):

Note

We write the Entity Framework for MVC module, but the pattern is the same or similar when applying to Web Application or Web API.

Introduction

This article is about Entity Framework with .Net MVC, Database-First approach.  This will be the easist and convenient one in the whole six approaches.

We will make a sample app step by step,

  • Step 1: Create an ASP.NET MVC application
  • Step 2: Reverse Engineer Model
  • Step 3: Create Controller to access data from entity framework
  • Step 4: Run the app

At the end, we will have an .Net MVC app that can consume a database directly through entity framework.

Step 1 - Create an ASP.NET MVC app

We use the current version of Visual Studio 2019 16.9.3 and .NET Framework 4.8 to build the app:

  • Start Visual Studio and select Create a new project.
  • In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next.
  • In the Configure your new project dialog, enter MVC_DatabaseFirst for Project name > Create.
  • In the Create a new ASP.NET Web Application dialog, select MVC > Creat

Note

For biginners, you may see details from here.

Build and run the app, you will see the following image shows the app,

Step 2, Reverse Engineer Model

We’re going to make use of Entity Framework Designer, which is included as part of Visual Studio, to create our model.

  • Project -> Add New Item…

  • Select Data from the left menu and then ADO.NET Entity Data Model

  • Enter StoreModel as the name and click OK

  • This launches the Entity Data Model Wizard

Select Generate from Database and click Next.

In the Choose Your Data Connection Dialog box, Click New Connection.

In the Connection Properties Dialog box, Choose Server Name: Localhost, and Select or Enter database name: Pubs, Click OK.

You got connection string, Click Next.

Click Next.

Click the checkbox next to ‘Tables’ to import stores and click Finish

Once the reverse engineer process completes the new model is added to your project and opened up for you to view in the Entity Framework Designer:

The created class Store like this

//------------------------------------------------------------------------------  
// <auto-generated>  
//     This code was generated from a template.  
//  
//     Manual changes to this file may cause unexpected behavior in your application.  
//     Manual changes to this file will be overwritten if the code is regenerated.  
// </auto-generated>  
//------------------------------------------------------------------------------  
  
namespace MVC_DatabaseFirst  
{  
    using System;  
    using System.Collections.Generic;  
      
    public partial class store  
    {  
        public string stor_id { get; set; }  
        public string stor_name { get; set; }  
        public string stor_address { get; set; }  
        public string city { get; set; }  
        public string state { get; set; }  
        public string zip { get; set; }  
    }  
} 

the Data Context will be in pubsEntities class:

//------------------------------------------------------------------------------    
// <auto-generated>    
//     This code was generated from a template.    
//    
//     Manual changes to this file may cause unexpected behavior in your application.    
//     Manual changes to this file will be overwritten if the code is regenerated.    
// </auto-generated>    
//------------------------------------------------------------------------------    
    
namespace MVC_DatabaseFirst    
{    
    using System;    
    using System.Data.Entity;    
    using System.Data.Entity.Infrastructure;    
        
    public partial class pubsEntities : DbContext    
    {    
        public pubsEntities()    
            : base("name=pubsEntities")    
        {    
        }    
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)    
        {    
            throw new UnintentionalCodeFirstException();    
        }    
        
        public virtual DbSet<store> stores { get; set; }    
    }    
}   

and the connection details for the database will be inserted into web.config file:

<connectionStrings>  
  <add name="pubsEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=pubs;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
</connectionStrings> 

Step 3:  Create Controller to access data from entity framework

From Visual Studio IDE,

  • Right-click the Controllers folder.

  • Select Add > New Scaffolded Item Or Controller to open the window Add New Scaffolded Item

  • In the Add New Scaffold Item dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add.;

  • In the Add Controller dialog box,

    • Select store (MVC_DatabaseFirst) for the Model class.
    • Select pubsEntities (MVC_DatabaseFirst) for the Data context class.
    • For the Controller name enter storesController.
    • Click Add.

Step 4: Run the app

Type domain/stores into the link, you will get:

Summary

The .NET MVC module for Database-First approach is easist to build with a black box like model: .edmx file group.

Reference


Similar Articles