目录
3.1 新建接口类文件夹IService,并在文件夹中创建IGetService接口
3.2 在IService文件夹中创建GetsService类,继承接口IGetService并实现
非开发工作,纯属兴趣爱好,写的不好的地方还请留言
一、开发环境
Visual Studio 2022
EF Core
SQL Server2019
ASP.NET Core 6
二、项目搭建
2.1 创建ASP.NET MVC项目
2.1.1 创建新项目
2.1.2 选择ASP.NET Core Web 应用(模型-视图-控制器)
2.1.3 输入项目名称,选择存放文件夹
2.1.4 选择框架(选择.NET6)后,点击创建
2.2 导入相关程序包
2.2.1 将所需要的三个程序包提过nuget导入
2.3 创建模型类、数据库上下文
2.3.1 Models文件夹下,创建模型类Student
public class Student
{
public int Id { get; set; }
public string ? Name { get; set; }
public int Age { get; set; }
public bool Sex { get; set; }
public string ? Address { get; set; }
}
2.3.2 项目下,添加Data文件夹,在Data文件夹中添加WebDbContext类
2.4 配置连接数据库、配置数据库上下文、注册数据库上下文
2.4.1 在appsettings.json文件中配置连接数据库
因为采用Code First模式,所以字符串中的Initial Catalog=Db_Web,对应的是将要创建的数据库名称,这里自行修改;
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"WebDbContext": "Data Source=.;Initial Catalog=Db_Web;Integrated Security=True;TrustServerCertificate=True"
}
}
2.4.2 在WebDbContext类中配置数据库上下文
using Microsoft.EntityFrameworkCore;
using WebAppMVC.Models;
namespace WebAppMVC.Data
{
public class WebDbContext:DbContext
{
public WebDbContext(DbContextOptions<WebDbContext> options) : base(options) { }
public DbSet<Student> Students { get; set; } //指定数据库创建的表名
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Student>().Property(e => e.Name).HasMaxLength(50);//指定数据库表字段的长度
modelBuilder.Entity<Student>().Property(e => e.Address).HasMaxLength(100);
}
}
}
2.4.3 在Program类中注册数据库上下文
// Add services to the container.
builder.Services.AddControllersWithViews();
//注册数据库上下文
builder.Services.AddDbContext<WebDbContext>(options=>
options.UseSqlServer(builder.Configuration.GetConnectionString("WebDbContext")));
var app = builder.Build();
2.5 数据迁移、添加初始数据
2.5.1在Data文件夹中添加SeedData类,并添加以下代码
using Microsoft.EntityFrameworkCore;
namespace WebAppMVC.Data
{
public static class SeedData
{
public static void SData(IServiceProvider serviceProvider)
{
WebDbContext context = null;
using (context = new WebDbContext(serviceProvider.GetRequiredService<DbContextOptions<WebDbContext>>()))
{
if (context.Students.Any())
{
return;
}
context.Students.AddRange(
new Models.Student() { Name = "张三", Age = 17, Sex = true, Address = "湖南长沙" },
new Models.Student() { Name = "李四", Age = 18, Sex = false, Address = "湖南长沙" },
new Models.Student() { Name = "王五", Age = 19, Sex = true, Address = "湖南长沙" },
new Models.Student() { Name = "赵六", Age = 20, Sex = false, Address = "湖南长沙" }
);
context.SaveChanges();
}
}
}
}
2.5.2 将初始化数据注册到服务中
// Add services to the container.
builder.Services.AddControllersWithViews();
//注册数据库上下文
builder.Services.AddDbContext<WebDbContext>(options=>
options.UseSqlServer(builder.Configuration.GetConnectionString("WebDbContext")));
//注册接口
builder.Services.AddScoped<IGetService<Student>,GetsService>();
var app = builder.Build();
using (var scope=app.Services.CreateScope())
{
var service=scope.ServiceProvider;
SeedData.SData(service);
}
2.5.3 在程序包管理控制台输入:Add-Migration initialcreate,之后再输入Update-DataBase,检查SQL server是否生成了数据库;
三、业务实现
3.1 新建接口类文件夹IService,并在文件夹中创建IGetService接口
namespace WebAppMVC.IService
{
public interface IGetService<T> where T : class
{
List<T> GetServices();
}
}
3.2 在IService文件夹中创建GetsService类,继承接口IGetService并实现
using WebAppMVC.Data;
using WebAppMVC.Models;
namespace WebAppMVC.IService
{
public class GetsService : IGetService<Student>
{
private readonly WebDbContext _db;
public GetsService(WebDbContext db)
{
_db = db;
}
public List<Student> GetServices()
{
var list=_db.Students.ToList();
return list;
}
}
}
3.3 将IGetService接口进行注册
// Add services to the container.
builder.Services.AddControllersWithViews();
//注册数据库上下文
builder.Services.AddDbContext<WebDbContext>(options=>
options.UseSqlServer(builder.Configuration.GetConnectionString("WebDbContext")));
//注册接口
builder.Services.AddScoped<IGetService<Student>,GetsService>();
var app = builder.Build();
3.4 创建StudentController控制器
using Microsoft.AspNetCore.Mvc;
using WebAppMVC.IService;
using WebAppMVC.Models;
namespace WebAppMVC.Controllers
{
public class StudentController : Controller
{
private readonly IGetService<Student> _service;
public StudentController(IGetService<Student> service)
{
_service = service;
}
public IActionResult Index()
{
var list = _service.GetServices();
return View();
}
}
}
3.5 创建Index视图
@{
ViewData["Title"] = "查询所有";
}
@model List<Student>
<div>
<table class="table table-bordered">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>住址</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@item.Age</td>
@if (item.Sex == true)
{
<td>男</td>
}
else
{
<td>女</td>
}
<td>@item.Address</td>
</tr>
}
</table>
</div>
四、运行结果
4.1 修改起始路由信息
app.MapControllerRoute(
name: "default",
pattern: "{controller=Student}/{action=Index}/{id?}");
app.Run();
4.2 运行结果
4.2 总结
该Demo涉及到的技术点包含:ASP.NET Core、MVC、EF Core、Code First,其中接口部分所使用泛型接口,第一次发表文章,有些地方可能描述有问题,还请见谅。
标签:Core,ASP,WebDbContext,builder,数据库,MVC,WebAppMVC,using,public From: https://blog.csdn.net/weixin_51164103/article/details/139468834