ASP NetMVC Core Working With Data EntityFrameworkCore Read Data
Working with Data in ASP.NET Core MVC Using Entity Framework Core
In the world of web development, seamless data handling is crucial for building efficient applications. ASP.NET Core MVC combined with Entity Framework Core offers a powerful framework for developing robust web applications. In this blog post, we will explore how to read data using Entity Framework Core in an ASP.NET Core MVC application.
Prerequisites
Before we get started, ensure you have the following:
- .NET Core SDK installed
- Visual Studio or Visual Studio Code
- Basic understanding of C# and ASP.NET Core MVC
- SQL Server (or any supported database) set up for your project
Setting Up the Project
First, let’s create a new ASP.NET Core MVC project:
- Open Visual Studio and click on "Create a new project."
- Select "ASP.NET Core Web Application" and click "Next."
- Name your project (e.g.,
MvcDataDemo) and choose a location to save it. Click "Create." - In the next window, select "Web Application (Model-View-Controller)" and ensure that "Enable Docker" is unchecked. Click "Create."
Adding Entity Framework Core
To work with Entity Framework Core, we need to add the necessary packages. You can do this via the NuGet Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Creating the Data Model
Next, we will create a simple data model representing a Product. Create a new folder named Models and add a class called Product.cs:
namespace MvcDataDemo.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Setting Up the Database Context
Now, let’s create a database context that will interact with the database. Create a new folder named Data and add a class called ApplicationDbContext.cs:
using Microsoft.EntityFrameworkCore;
using MvcDataDemo.Models;
namespace MvcDataDemo.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
}
Configuring the Database Connection
Next, we need to configure the database connection in appsettings.json. Add a connection string under the ConnectionStrings section:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MvcDataDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
},
...
}
Then, open Startup.cs and register the database context within the ConfigureServices method:
using MvcDataDemo.Data;
using Microsoft.EntityFrameworkCore;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
}
Creating the Controller
Now, let’s create a controller to manage our Product data. In the Controllers folder, add a class called ProductsController.cs:
using Microsoft.AspNetCore.Mvc;
using MvcDataDemo.Data;
using MvcDataDemo.Models;
using System.Linq;
namespace MvcDataDemo.Controllers
{
public class ProductsController : Controller
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var products = _context.Products.ToList();
return View(products);
}
}
}
Creating the View
Next, we need to create a view to display our products. In the Views/Products folder, create a file called Index.cshtml:
@model IEnumerable<MvcDataDemo.Models.Product>
<h1>Products</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Id</td>
<td>@product.Name</td>
<td>@product.Price</td>
</tr>
}
</tbody>
</table>
Running the Application
You are now ready to run your application. Open Startup.cs, and ensure the routing is configured correctly:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Products}/{action=Index}/{id?}");
});
Now, run your application, and navigate to /Products. You should see a table displaying the products from your database.
Conclusion
In this tutorial, we’ve covered the basics of setting up an ASP.NET Core MVC application to read data using Entity Framework Core. We created a simple data model, set up a database context, created a controller, and displayed the data in a view.
Entity Framework Core simplifies database operations, allowing developers to focus on building features rather than writing complex SQL queries. By following this tutorial, you have laid the groundwork for more complex data interactions in your ASP.NET Core MVC applications.
Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment