Data Access in ASP.NET Core MVC
Introduction to Data Access
In ASP.NET Core MVC applications, interacting with data is a fundamental requirement. This typically involves connecting to databases, retrieving data, and persisting changes. This module explores common patterns and technologies for data access.
Entity Framework Core
Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET. It allows developers to work with a database using .NET objects and LINQ queries, abstracting away much of the underlying SQL code.
Key Concepts:
- DbContext: Represents a session with the database and allows you to query and save data.
- DbSet: A collection of entities of a particular type.
- Migrations: A feature of EF Core that allows you to manage database schema changes over time.
Setup:
To use EF Core, you'll need to install the appropriate NuGet packages. For SQL Server, you'd typically install:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Example Model and DbContext:
Models/Product.cs
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
}
Registering DbContext in Startup:
Startup.cs (ConfigureServices method)
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Ensure you have a connection string in your appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Working with Data in Controllers
You can inject your DbContext into controllers to perform CRUD (Create, Read, Update, Delete) operations.
Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class ProductsController : Controller
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _context.Products.ToListAsync());
}
// GET: Products/Create
public IActionResult Create()
{
return View();
}
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ProductId,Name,Price")] Product product)
{
if (ModelState.IsValid)
{
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(product);
}
// ... other CRUD actions (Details, Edit, Delete)
}
Repository Pattern (Optional)
For more complex applications, the Repository Pattern can provide an additional layer of abstraction, separating the data access logic from the business logic and controllers.
This pattern involves creating interfaces for data operations and concrete implementations that use EF Core.
Other Data Access Technologies
While EF Core is popular, other options exist:
- Dapper: A high-performance, lightweight micro-ORM.
- ADO.NET: The foundational data access technology in .NET, offering direct control over SQL commands.
- NoSQL Databases: For specific use cases, databases like MongoDB, Cassandra, or Azure Cosmos DB can be integrated using their respective drivers.
Next Steps
Continue to the next module on Validation to learn how to ensure data integrity.