In this article we will discuss How to use entity framework in ASP.Net Core MVC.
Here we will explain how to configure Entity Framework and connect to SQL Server database and displayed in View in ASP.Net Core MVC..
Before start this article, please visit our previous article Populating DropDownList inside Razor Pages in ASP.Net Core MVC
Database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE [dbo].[States]( | |
[stateAbbrev] [nchar](10) NULL, | |
[stateName] [nchar](20) NULL, | |
[stateID] [smallint] NOT NULL | |
) ON [PRIMARY] | |
GO |
Downloading Entity Framework Core
You will need to install the Microsoft.EntityFrameworkCore.SqlServer package using the following command.
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.1.1
Model
Let's create a class in Models folder like below.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class States | |
{ | |
[Key] | |
public Int16 stateID { get; set; } | |
public string stateName { get; set; } | |
public string stateAbbrev { get; set; } | |
} |
Database Context
Now you will need to add a new class to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
Inside the class, first inherit the EntityFrameworkCore namespace and then inherit the DbContext class.
Then using Dependency Injection, a Constructor is created DbContextOptions are passed as parameter and also the Constructor of base class i.e. DbContext class is inherited.
Finally, a DbSet Collection property of Customer Model class is created, which will be later used for holding the Data fetched from SQL Server Database Table.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DBContextEF : DbContext | |
{ | |
public DBContextEF(DbContextOptions<DBContextEF> options) : base(options) | |
{ | |
} | |
public DbSet<States> States { get; set; } | |
} |
Adding the Connection String inside AppSettings.json
The following Connection String setting has been added in the AppSettings.json file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Logging": { | |
"LogLevel": { | |
"Default": "Information", | |
"Microsoft": "Warning", | |
"Microsoft.Hosting.Lifetime": "Information" | |
} | |
}, | |
"AllowedHosts": "*", | |
"ConnectionStrings": { | |
"DBConnection": "Data Source=MSCNUR1888004;Initial Catalog=DentalJobs;Integrated security=true" | |
} | |
} |
Configuring Database Context in Startup class
Inside the Startup class, the IConfiguration is injected in the Startup class and assigned to the private property Configuration.
Then the Connection String is read from the AppSettings.json file and is used to add the DbContext service.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddControllersWithViews(); | |
string conStr = this.Configuration.GetConnectionString("DBConnection"); | |
services.AddDbContext<DBContextEF>(options => options.UseSqlServer(conStr)); | |
} |
Controller
Inside the Index Action method, the Top 10 records are fetched from the States Table.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HomeController : Controller | |
{ | |
private readonly ILogger<HomeController> _logger; | |
private DBContextEF Context { get; } | |
public HomeController(ILogger<HomeController> logger, DBContextEF _context) | |
{ | |
_logger = logger; | |
this.Context = _context; | |
} | |
public IActionResult Index() | |
{ | |
List<States> states = Context.States.Take(10).ToList(); | |
return View(states); | |
} | |
} |
View
Inside the View, in the very first line the State Entity is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the State records.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@using MVCCore.EF.Models | |
@model IEnumerable<States> | |
@{ | |
ViewData["Title"] = "Home Page"; | |
} | |
<div class="text-center"> | |
<h4>State List</h4> | |
<hr /> | |
<table class="table table-bordered"> | |
<tr> | |
<th>State ID</th> | |
<th>State Name</th> | |
<th>State Abbreviation</th> | |
</tr> | |
@foreach (States state in Model) | |
{ | |
<tr> | |
<td>@state.stateID</td> | |
<td>@state.stateName</td> | |
<td>@state.stateAbbrev</td> | |
</tr> | |
} | |
</table> | |
</div> |
Output
When run the application we can see the output like below.