English translation
Data Access with Entity Framework Core in ASP.NET Core
AI Article Decision Snapshot
Turn the lesson into workflow, model, budget, and security checks before choosing tools.
Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.
Workflow fit
Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.
Model or tool decision
Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.
Budget and usage signal
Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.
Security and privacy review
Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.
In the previous section of our ASP.NET Core framework tutorial, we explored how dependency injection helps manage dependencies and improves code testability. In this section, we’ll dive deeper into using Entity Framework Core for data access. Entity Framework Core (commonly abbreviated as EF Core) is a modern object-relational mapping (ORM) framework that enables straightforward interaction with databases.
What Is Entity Framework Core?
Entity Framework Core is a lightweight, extensible, open-source ORM framework designed for .NET applications. It allows developers to interact with databases using C# code—without writing complex SQL queries.
Configuring Entity Framework Core
Installing NuGet Packages
Before using Entity Framework Core, you must install the required NuGet packages. You can do this via the NuGet Package Manager or the command-line interface. Below are the CLI commands to install the SQL Server provider and EF Core tools:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Creating a DbContext
The DbContext class serves as the primary entry point for interacting with the database. In our example, we’ll create a BlogDbContext to model our blog application:
public class BlogDbContext : DbContext
{
public BlogDbContext(DbContextOptions<BlogDbContext> options) : base(options) { }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
Registering DbContext in the Dependency Injection Container
Ensure the DbContext is registered in the dependency injection container inside Startup.cs, specifically within the ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BlogDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Other services
services.AddControllersWithViews();
}
Configuring the Database Connection String
Add the database connection string to appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlogDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
// Other configuration settings
}
Performing CRUD Operations with Entity Framework Core
Next, let’s implement Create, Read, Update, and Delete (CRUD) operations using Entity Framework Core inside a controller.
Creating a Controller
using Microsoft.AspNetCore.Mvc;
using System.Linq;
public class BlogsController : Controller
{
private readonly BlogDbContext _context;
public BlogsController(BlogDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var blogs = _context.Blogs.ToList();
return View(blogs);
}
[HttpPost]
public IActionResult Create(Blog blog)
{
if (ModelState.IsValid)
{
_context.Blogs.Add(blog);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View(blog);
}
public IActionResult Edit(int id)
{
var blog = _context.Blogs.SingleOrDefault(b => b.BlogId == id);
if (blog == null)
{
return NotFound();
}
return View(blog);
}
[HttpPost]
public IActionResult Edit(Blog blog)
{
if (ModelState.IsValid)
{
_context.Blogs.Update(blog);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View(blog);
}
public IActionResult Delete(int id)
{
var blog = _context.Blogs.SingleOrDefault(b => b.BlogId == id);
if (blog == null)
{
return NotFound();
}
_context.Blogs.Remove(blog);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
}
Displaying Data Using Razor Views
In Views/Blogs/Index.cshtml, we render the list of blogs:
@model IEnumerable<Blog>
<h2>Blogs</h2>
<table>
<thead>
<tr>
<th>BlogId</th>
<th>Url</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var blog in Model)
{
<tr>
<td>@blog.BlogId</td>
<td>@blog.Url</td>
<td>
<a asp-action="Edit" asp-route-id="@blog.BlogId">Edit</a>
<form asp-action="Delete" asp-route-id="@blog.BlogId" method="post" style="display:inline;">
<button type="submit">Delete</button>
</form>
</td>
</tr>
}
</tbody>
</table>
<a asp-action="Create">Create New</a>
Summary
In this section, we learned how to use Entity Framework Core for data access: we created a DbContext, configured the database connection, and implemented fundamental CRUD operations. This foundation prepares us for more advanced scenarios—particularly database migrations—in upcoming sections.
By promoting maintainability and scalability, Entity Framework Core delivers powerful capabilities that significantly streamline data layer development in ASP.NET Core applications.
Apply This Lesson
Turn this article into AI software, model, API, and security decisions.
English Article FAQ
Use this article as evidence before choosing AI tools
How should I use this AI Tutorials article?
Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.
Is this English article different from the Chinese original?
The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.
What should I read after Data Access with Entity Framework Core in ASP.NET Core?
Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.
Can this article alone choose an AI product or model?
No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.
Continue