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):
- Entity Framework (0), Overview
- Entity Framework (1), with .Net MVC, Code-First
- Entity Framework (2), with .Net MVC, Database-First --- this article
- Entity Framework (3), with .Net MVC, Model-First
- Entity Framework (4), with .Net Core MVC, Code-First
- Entity Framework (5), with .Net Core MVC, Database-First
- Entity Framework (6), with .Net Core MVC, Model-First
- Entity Framework (7), with .Net WPF, Database-First
- Entity Framework (8), with .NET Core Web API, Stored Procedure
- Entity Framework (9), with .NET Core Web API, Stored Procedure Implementation
- Entity Framework (10), with .Net WebForms, Database-First
- Entity Framework (11), with .Net Core Razor Pages Code-First
- Entity Framework (12), with New .Net Core MVC Code-First
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.
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 (StoreModel.edmx):
The created class Store like this (StoreModel.edmx/StoreModel.tt/store.cs)
//------------------------------------------------------------------------------
// <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 (StoreModel.edmx/StoreModel.Context.tt/StoreModel.Context.cs):
//------------------------------------------------------------------------------
// <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