- 环境
- 开发平台:NET6
- 数据库:MSSQLLocalDB
- 开发工具:VS2022
- 操作系统:Windows11
- ORM:Entity FrameworkCore
- 创建一个ASP.NET Core Web 应用项目 EFDemo。
- 添加数据库链接语句,在appsettings.json文件中添加ConnectionStrings、DefaultStringappsettings.json文件内容如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Persion;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
}
}
4. 添加EntityFrameworkCroe的NuGet包如下:
4.1、Microsoft.EntityFrameworkCore Version="6.0.27"
4.2、Microsoft.EntityFrameworkCore.Design Version="6.0.27"
4.3、Microsoft.EntityFrameworkCore.SqlServer Version="6.0.27"
4.4、Microsoft.EntityFrameworkCore.Tools Version="6.0.27"
5.选择“视图->其他窗口->程序包管理器控制台”,查看EntityFramework帮助输入命令如下:
Get-Help about_EntityFrameworkCore
6.在项目中添加文件夹“Models”、“Data”
6.1、“Models”文件夹中添加Persion类,代码如下:
public class Persion
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
6.2、 “Data”文件夹中添加DataContext类,代码如下:
using EFDemo.Models;
using Microsoft.EntityFrameworkCore;
namespace EFDemo.Data
{
public class DataContext:DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
//DbSet属性
public DbSet<Persion> Persions { get; set; }
}
}
6.3、向Program.cs文件中添加代码,
builder.Services.AddDbContext<DataContext>(options =>
{
//链接MSSQL
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultString"));
});
6.4、builder.Services.AddDbContext<DataContext>();
Program.cs文件代码如下:
using EFDemo.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<DataContext>(options =>
{
//链接MSSQL
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultString"));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/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.MapRazorPages();
app.Run();
6.5、在程序包管理器控制台中输入Add-Migration InitPersion,项目目录中自动生成了Migrations文件夹,文件夹中包含两个迁移文件。注意此时没有生成数据库
在程序包管理器控制台中输入Update-Database -Verbose,-Verbose用于显示详细的生成数据库的过程。此时在“视图->SQL Server对象资源管理器”中查看生成的数据库。
到这里Entity Framework的迁移操作已经完成,接下来我们来操作一下数据接口。
向项目添加MVC功能, 在Program.cs文件中添加语句。
添加语句如下:
//添加MVC
builder.Services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
//使用MVC
app.UseMvc(routes =>
{
routes.MapRoute("Default", "{Controller}/{Action}/{id?}");
});
6.6、Program.cs文件代码如下:
using EFDemo.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
//添加MVC
builder.Services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
builder.Services.AddDbContext<DataContext>(options =>
{
//链接MSSQL
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultString"));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/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.MapRazorPages();
//使用MVC
app.UseMvc(routes =>
{
routes.MapRoute("Default", "{Controller}/{Action}/{id?}");
});
app.Run();
6.7、项目中添加Controllers文件夹,添加控制器HomeController。控制器中代码如下:
using EFDemo.Data;
using EFDemo.Models;
using Microsoft.AspNetCore.Mvc;
using System;
namespace EFDemo.Controllers
{
[Route("Home")]
public class HomeController : Controller
{
private readonly DataContext _dataContext;
public HomeController(DataContext dataContext)
{
_dataContext = dataContext;
}
[Route("Create")]
[HttpGet]
public IActionResult Create()
{
Persion _persion1 = new Persion() { Age = "18", Name = "Persion1" };
Persion _persion2 = new Persion() { Age = "18", Name = "Persion2" };
Persion _persion3 = new Persion() { Age = "18", Name = "Persion3" };
Persion _persion4 = new Persion() { Age = "18", Name = "Persion4" };
Persion _persion5 = new Persion() { Age = "18", Name = "Persion5" };
_dataContext.Persions.Add(_persion1);
_dataContext.Persions.Add(_persion2);
_dataContext.Persions.Add(_persion3);
_dataContext.Persions.Add(_persion4);
_dataContext.Persions.Add(_persion5);
_dataContext.SaveChanges();
return Ok("数据创建成功");
}
[Route("Get")]
[HttpGet]
public IActionResult Get(int? id)
{
object _object = _dataContext.Persions.Find(id);
return Ok(_object);
}
}
}
6.8、运行起项目后,在浏览器分别输入,其中7260是端口号,每台机器的端口号可能是不一样的:
6.8.1、https://localhost:7260/Home/Create
6.8.2、https://localhost:7260/Home/Get/?id=3