This tutorial section focuses on how to effectively manage and display data within your ASP.NET Core MVC applications. We'll explore common data access patterns and how to integrate them with your controllers and views.
ASP.NET Core MVC applications often need to interact with data sources, such as databases, APIs, or flat files. The Model-View-Controller (MVC) pattern provides a clean separation of concerns, making data handling more organized and maintainable.
Common data access technologies include:
For this tutorial, we'll primarily use Entity Framework Core due to its popularity and ease of use with ASP.NET Core.
To use EF Core, you need to add the necessary NuGet packages to your project.
Open the Package Manager Console (Tools > NuGet Package Manager > Package Manager Console) and run:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
The SqlServer package is for SQL Server, but you can replace it with packages for other databases like Npgsql.EntityFrameworkCore.PostgreSQL for PostgreSQL or Pomelo.EntityFrameworkCore.MySql for MySQL.
Next, configure your database context in Startup.cs (or Program.cs in .NET 6+). This class acts as a session with the database and allows you to query and save data.
Example Startup.cs (or Program.cs for .NET 6+):
// In ConfigureServices method (Startup.cs) or Program.cs
// using YourProject.Data; // Assuming your DbContext is in a Data folder
// services.AddDbContext(options =>
// options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Define your connection string in appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
// ... other settings
}
Create Plain Old CLR Objects (POCOs) to represent your data. These will map to your database tables.
Example Model (Models/Product.cs):
namespace YourProject.Models
{
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
}
}
In your DbContext, include a DbSet<TEntity> property for each model:
using Microsoft.EntityFrameworkCore;
using YourProject.Models;
namespace YourProject.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
// Add DbSet for other models here
}
}
Create database migrations to apply your model changes to the database:
Add-Migration InitialCreate
Update-Database
Inject your DbContext into your controllers to retrieve and manipulate data.
Example Controller (Controllers/ProductsController.cs):
using Microsoft.AspNetCore.Mvc;
using YourProject.Data;
using YourProject.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace YourProject.Controllers
{
public class ProductsController : Controller
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
// GET: /products
public async Task<IActionResult> Index()
{
var products = await _context.Products.ToListAsync();
return View(products);
}
// GET: /products/details/5
public async Task<IActionResult> Details(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// GET: /products/create
public IActionResult Create()
{
return View();
}
// POST: /products/create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ProductId,Name,Price,Description")] Product product)
{
if (ModelState.IsValid)
{
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(product);
}
// ... other actions like Edit, Delete
}
}
Create Razor views to display the data passed from the controller.
Example View for Index (Views/Products/Index.cshtml):
@model IEnumerable<YourProject.Models.Product>
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<h1>Products List</h1>
<p>
<a asp-action="Create">Create New Product</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<a asp-action="Details" asp-route-id="@item.ProductId">Details</a> |
<a asp-action="Edit" asp-route-id="@item.ProductId">Edit</a> |
<a asp-action="Delete" asp-route-id="@item.ProductId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
<style>
.table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.table th, .table td {
border: 1px solid #ddd;
padding: 10px;
text-align: left;
}
.table th {
background-color: #f2f2f2;
font-weight: bold;
}
.table tbody tr:nth-child(even) {
background-color: #f9f9f9;
}
.table tbody tr:hover {
background-color: #e6f0ff;
}
.table a {
margin-right: 8px;
}
</style>