ASP.NET Core 入门教程三 结合 EFCore 和 SQLite

ASP.NET Core 是一个开源的 Web 框架,它允许开发者轻松地构建现代、高性能的 Web 应用程序。Entity Framework Core (EFCore) 是一个轻量级、可扩展的 ORM(对象关系映射)框架,它支持多种数据库。SQLite 是一个轻量级的嵌入式数据库,适用于小型应用程序。在本篇文章中,我们将学习如何在 ASP.NET Core 项目中结合 EFCore 和 SQLite。

1. 创建一个新的 ASP.NET Core Web API 项目

首先,我们需要创建一个新的 ASP.NET Core Web API 项目。在 Visual Studio 中,选择 "创建新项目",然后选择 "ASP.NET Core Web 应用程序"。在 "选择模板" 对话框中,选择 ".NET Core" 和 "API" 模板。为项目命名并单击 "创建"。

2. 安装 EFCore 和 SQLite 相关包

在项目中,我们需要安装 EFCore 和 SQLite 相关的 NuGet 包。右键单击项目名称,选择 "管理 NuGet 程序包",然后搜索并安装以下包:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Sqlite
  • Microsoft.EntityFrameworkCore.Tools

3. 创建实体类和数据库上下文

接下来,我们需要创建一个实体类和一个继承自 DbContext 的数据库上下文类。

复制代码
cs 复制代码
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=./products.db");
    }
}

在上面的代码中,我们创建了一个 Product 实体类和一个 AppDbContext 数据库上下文类。DbSet<Product> 表示 Product 实体将在数据库中映射为一个表。OnConfiguring 方法用于配置数据库连接字符串。

4. 迁移数据库

在 EFCore 中,我们可以使用迁移来创建和更新数据库结构。首先,我们需要创建一个迁移。在 Visual Studio 的 "包管理器控制台" 中,输入以下命令:

复制代码
复制代码
Add-Migration InitialCreate

这将创建一个名为 "InitialCreate" 的迁移。接下来,我们需要应用这个迁移来创建数据库:

复制代码
复制代码
Update-Database

现在,数据库和 Products 表已经创建好了。

5. 实现 CRUD 操作

最后,我们将在控制器中实现基本的 CRUD 操作。

复制代码
cs 复制代码
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace YourProjectName.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        private readonly AppDbContext _context;

        public ProductsController(AppDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        public IActionResult GetProducts()
        {
            return _context.Products.ToList();
        }

        [HttpGet("{id}")]
        public IActionResult GetProduct(int id)
        {
            var product = _context.Products.Find(id);
            if (product == null)
            {
                return NotFound();
            }
            return product;
        }

        [HttpPost]
        public IActionResult CreateProduct([FromBody] Product product)
        {
            _context.Products.Add(product);
            _context.SaveChanges();
            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
        }

        [HttpPut("{id}")]
        public IActionResult UpdateProduct(int id, [FromBody] Product productDetails)
        {
            var product = _context.Products.Find(id);
            if (product == null)
            {
                return NotFound();
.
相关推荐
llz_1126 分钟前
web-第二次课后作业
前端·后端·web
红尘散仙6 小时前
我把终端小说阅读器接上了 AI Agent:TRNovel 现在能用 skill 生成书源了
人工智能·后端·rust
卷毛的技术笔记7 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
会编程的土豆8 小时前
Go 语言反射(Reflection)详解
开发语言·后端·golang
喵个咪8 小时前
GoWind Toolkit Go后端代码生成 完整全流程实战
后端·go·orm
basketball6168 小时前
Go 语言从入门到进阶:4. 数组和MAP使用方法总结
开发语言·后端·golang
qq_2518364578 小时前
SpringBoot+Vue 共享电池柜管理系统 完整实现 前后端分离项目实战 完整代码
vue.js·spring boot·后端
zhangxingchao9 小时前
AI 大模型核心六:量化、Workflow 与 Agent、多轮 RAG
前端·人工智能·后端
IT_陈寒10 小时前
Vite打包时遇到的坑,原来问题出在这里
前端·人工智能·后端
ayqy贾杰11 小时前
基层管理的三板斧,在AI时代行不通了
前端·后端·团队管理