赞
踩
随着技术的发展,ASP.NET Core MVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NET Core MVC开发B/S系统过程中所涉及到的相关内容,适用于初学者,在校毕业生,或其他想从事ASP.NET Core MVC 系统开发的人员。 经过前几篇文章的讲解,初步了解ASP.NET Core MVC项目创建,启动运行,以及命名约定,创建控制器,视图,模型,接收参数,传递数据,路由,页面布局,wwwroot和客户端库,Razor语法等内容,今天继续讲解ASP.NET Core MVC 中EnityFrameworkCore与数据库等相关内容,仅供学习分享使用。
Entity Framework (EF) Core 是轻量化、可扩展、开源和跨平台版的常用 Entity Framework 数据访问技术。
EF Core 可用作对象关系映射程序 (O/RM),这可以实现以下两点:
在ASP.NET Core MVC项目中,环境搭建常有两种模式:Code First和DB First,在本例中主要采用DB First模式,使用的数据库为SQL Server 2012。首先创建数据库,并命名称MovieDB,然后创建数据表Movie,如下所示:
通过数据库右键进行创建数据库,创建表的语句如下所示:
- USE [MovieDB]
- GO
-
- /****** Object: Table [dbo].[Movie] Script Date: 2023/4/25 23:53:21 ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[Movie](
- [Id] [bigint] IDENTITY(1,1) NOT NULL,
- [Name] [varchar](200) NULL,
- [ReleaseDate] [datetime] NULL,
- [LeadingRole] [varchar](100) NULL,
- [Genre] [varchar](100) NULL,
- [Price] [money] NULL,
- [CreateTime] [datetime] NULL,
- [CreateUser] [varchar](50) NULL,
- [LastEditTime] [datetime] NULL,
- [LastEditUser] [varchar](50) NULL,
- CONSTRAINT [PK_Movie] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- SET ANSI_PADDING OFF
- GO
在测试应用之前,首先在数据表中插入2条测试数据,以便看到效果,如下所示:
数据库和数据表创建成功后,需要ASP.NET Core MVC项目中创建与数据表对应的实体类MovieEntity,如下所示:
- namespace DemoCoreMVC.Entities
- {
- /// <summary>
- /// 电影实体
- /// </summary>
- public class MovieEntity
- {
- /// <summary>
- /// 主键唯一标识
- /// </summary>
- public long Id { get; set; }
-
- /// <summary>
- /// 电影名称
- /// </summary>
- public string Name { get; set; }
-
- /// <summary>
- /// 发行时间
- /// </summary>
- public DateTime ReleaseDate { get; set; }
-
- /// <summary>
- /// 主角
- /// </summary>
- public string LeadingRole { get; set; }
-
- /// <summary>
- /// 电影类型
- /// </summary>
- public string Genre { get; set; }
-
- /// <summary>
- /// 票价格
- /// </summary>
- public decimal Price { get; set; }
-
- /// <summary>
- /// 创建时间
- /// </summary>
- public DateTime CreateTime { get; set; }
-
- /// <summary>
- /// 录入人员
- /// </summary>
- public string CreateUser { get; set; }
-
- /// <summary>
- /// 最后编辑时间
- /// </summary>
- public DateTime LastEditTime { get; set; }
-
- /// <summary>
- /// 最后编辑人员
- /// </summary>
- public string LastEditUser { get; set; }
- }
- }
实体用于和数据表进行映射,业务模型用于在控制器和视图之间进行数据的交互,所以为了进行分层和数据隔离,需要创建模块,在本例中模型为Movie,字段名称和Entity保持一致【也可以不一致】。如下所示:
- namespace DemoCoreMVC.Models
- {
- public class Movie
- {
- /// <summary>
- /// 主键唯一标识
- /// </summary>
- public long Id { get; set; }
-
- /// <summary>
- /// 电影名称
- /// </summary>
- public string Name { get; set; }
-
- /// <summary>
- /// 发行时间
- /// </summary>
- public DateTime ReleaseDate { get; set; }
-
- /// <summary>
- /// 主角
- /// </summary>
- public string LeadingRole { get; set; }
-
- /// <summary>
- /// 电影类型
- /// </summary>
- public string Genre { get; set; }
-
- /// <summary>
- /// 票价格
- /// </summary>
- public decimal Price { get; set; }
-
- }
- }
在ASP.NET Core MVC项目中,我们使用EntityFrameworkCore操作数据库,需要安装依赖包,通过Nuget包管理器进行安装,目前版本为7.0.5,如下所示:
在appsettings.json中,增加数据库连接字符串,配置ConnectionStrings节点,如下所示:
- {
- "ConnectionStrings": {
- "Default": "Server=数据库url;Database=MovieDb;User Id=数据库账号;Password=数据库密码;Trusted_Connection=True;;TrustServerCertificate=true;MultipleActiveResultSets=true"
- },
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
- }
- },
- "AllowedHosts": "*"
- }
EntityFrameCore通过DbContext操作数据,所以需要创建属于整个项目的数据上下文,并继承于DbContext,如下所示:
- using DemoCoreMVC.Entities;
- using Microsoft.EntityFrameworkCore;
-
- namespace DemoCoreMVC
- {
- public class MovieDbContext:DbContext
- {
- public MovieDbContext(DbContextOptions<MovieDbContext> options)
- : base(options)
- {
- }
-
- public DbSet<MovieEntity> Movie { get; set; }
-
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- base.OnModelCreating(modelBuilder);
- modelBuilder.Entity<MovieEntity>().ToTable("Movie");
- }
- }
- }
注意:在OnModelCreating中,将实体和数据表进行映射。
在Program.cs中,注入框架,并将appSetting.json配置的数据库连接字符串传递进去,如下所示:
- using DemoCoreMVC;
- using Microsoft.EntityFrameworkCore;
-
- var builder = WebApplication.CreateBuilder();
-
- //注入数据库框架
- builder.Services.AddDbContext<MovieDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
-
- // Add services to the container.
- builder.Services.AddControllersWithViews();
- var app = builder.Build();
-
- // Configure the HTTP request pipeline.
- if (!app.Environment.IsDevelopment())
- {
- app.UseExceptionHandler("/Home/Error");
- // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
- app.UseHsts();
- }
- app.UseHttpsRedirection();
- app.UseStaticFiles();
- app.UseRouting();
- app.UseAuthorization();
- app.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id?}");
-
- app.Run();
在项目中,创建MovieController,在Index方法中查询电影信息,并将数据传递给视图,如下所示:
- using DemoCoreMVC.Models;
- using Microsoft.AspNetCore.Mvc;
-
- namespace DemoCoreMVC.Controllers
- {
- public class MovieController : Controller
- {
- private MovieDbContext movieDb;
-
- public MovieController(MovieDbContext movieDb)
- {
- this.movieDb = movieDb;
- }
-
- public IActionResult Index()
- {
- //1.获取数据库实体
- var entities = movieDb.Movie.Skip(0).Take(20).ToList();
- //2.将实体转换成业务模型
- var movies = entities.Select(e => new Movie()
- {
- Id = e.Id,
- Name = e.Name,
- Genre = e.Genre,
- LeadingRole = e.LeadingRole,
- Price = e.Price,
- ReleaseDate = e.ReleaseDate,
- }).ToList();
- ViewData.Add("Movies",movies);
- return View();
- }
- }
- }
视图用于显示电影列表,代码如下所示:
- @{
- ViewData["Title"] = "Index";
- var movies = ViewData["Movies"] as List<Movie>;
- }
-
- <h1>Index</h1>
- <table class="table">
- <thead>
- <tr>
- <td>序号</td>
- <td>电影名称</td>
- <td>类型</td>
- <td>主演</td>
- <td>上映时间</td>
- <td>票价</td>
- <td>功能</td>
- </tr>
- </thead>
- @for (var i = 0; i < movies.Count; i++)
- {
- var movie = movies[i];
- <tr>
- <td>@movie.Id</td>
- <td>@movie.Name</td>
- <td>@movie.Genre</td>
- <td>@movie.LeadingRole</td>
- <td>@movie.ReleaseDate</td>
- <td>@movie.Price</td>
- <td><a href="/Movie/Edit/@movie.Id">编辑</a> | <a href="/Movie/Delete/@movie.Id">删除</a></td>
- </tr>
- }
- </table>
经过上述步骤,程序已经搭建完成,运行程序并输入URL:https://localhost:7152/Movie,打开效果如下所示:
本文主要参考文章如下:
数据库故障排查:https://learn.microsoft.com/zh-cn/troubleshoot/sql/welcome-sql-server
ASP.NET Core MVC入门之数据库:https://learn.microsoft.com/zh-cn/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-7.0&tabs=visual-studio
以上就是ASP.NET Core MVC从入门到精通之数据库的全部内容,旨在抛砖引玉,一起学习,共同进步。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。