上一篇 CRUD 使用的是模拟数据,本篇完成真正数据库的访问。由于 Sql Server 是微软自家数据库,天然友好,所以数据库我选择了 sql server,且使用微软的 SQL Server Express LocalDB。LocalDB 比 Express 版更加轻量级,甚至不用在 PC 上单独安装。
SQL Server Express LocalDB
在 Visual Studio 2019 中,通过菜单 【View】-> 【SQL Server Object Explorer】打开数据库浏览窗口。在该界面中,可以进行数据库的常见操作,比如新建数据库、定义表、执行 sql 语句、维护数据等。选中 Databases 导航菜单,右键 Add New Database,新建一个名为 StudentDb 的数据库:

为了后面连接字符串更加方便,不要更改数据库文件的位置,接受默认的位置:

用可视化的方式新建 Students 表:

如果习惯用 sql 语句,也可以在 Visual Studio 中使用 DDL 来创建表:
CREATE TABLE [dbo].[Students] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Major] NVARCHAR (50) NULL,
[Email] NVARCHAR(100) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
然后插入一些数据:
INSERT INTO [dbo].[Students] ([Id], [Name], [Major], [Email]) VALUES (1, N'张三', N'计算机技术', N'zs@qq.com')
INSERT INTO [dbo].[Students] ([Id], [Name], [Major], [Email]) VALUES (2, N'李四', N'人工智能', N'ls@qq.com')
INSERT INTO [dbo].[Students] ([Id], [Name], [Major], [Email]) VALUES (3, N'王五', N'电子商务', N'ww@qq.com')
EF Core
在 asp.net core 中通过 EF core 访问数据库,需要以下几个步骤:
1、安装 Entity Framework Core 相关的包,需要安装如下两个包。 NuGet 安装包的方法这里就不展开了。

2、连接字符串
将连接字符串写在 appsettings.json 文件中,连接字符串的写法如下:

3、新建 ApplicationDbContext 类,该类继承自 DbContext,DbContext 表示与数据库的一次会话,EF Core 中「增删改查」操作都基于该类。在 ApplicationDbContext 的类中定义 DbSet 属性,把 .Net 对象与数据库中的实体进行关联。

4、定义 Student model。我们在之前已经完成,所以这里省略
5、定义 IStudentRepository,包含如下接口方法:

6、定义基于 Sql Server 的实现:
namespace StudentManagement.Models
{
public class MsSqlStudentRepository : IStudentRepository
{
private readonly ApplicationDbContext dbContext;
public MsSqlStudentRepository(ApplicationDbContext context)
{
dbContext = context;
}
public Student Create(Student student)
{
dbContext.Students.Add(student);
dbContext.SaveChanges();
return student;
}
public Student Delete(int id)
{
var s = dbContext.Students.Find(id);
if (s != null)
{
dbContext.Students.Remove(s);
dbContext.SaveChanges();
}
return s;
}
public IEnumerable<Student> GetAllStudents()
{
return dbContext.Students;
}
public Student GetStudent(int id)
{
return dbContext.Students.Find(id);
}
public Student Update(Student student)
{
var s = dbContext.Students.Attach(student);
s.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
dbContext.SaveChanges();
return student;
}
}
}
7、在 startup.cs 中对 IStudentRepository 进行注册:

源码
源码托管在 gitee,项目名称: aspnetcore-studentmanagement,为了记录完整的编写过程,重要的步骤提交 tag 进行标记,本次代码 tag 为 v0.04。
本文介绍了如何在Visual Studio 2019环境中,通过Entity Framework Core (EFCore)与SQL Server Express LocalDB配合,进行数据库的创建、表设计、数据插入及基本的CRUD操作。详细步骤包括设置连接字符串、创建数据库、定义并填充学生表,并展示了如何在ApplicationDbContext和IStudentRepository接口中实现EFCore操作。

2709

被折叠的 条评论
为什么被折叠?



