- IDE: Visual Studio community
- DB:MySQL5.7+
- .net SDK - x64
准备
File-》New-》Project
ASP.NET Core Web Application(Model-View-Controller)

Additional information
- .Net 10.0(Lts)
- Authentication type
None
- Configure for HTTPS
checked
Web Server
- http
- https
default
-
IIS Express
点击“IIS Express”运行(如果弹出证书安装选“是”即可)。

Demo

Repository
Project-》Manage NuGet Packages
entity class
数据表的Entity类
using System.ComponentModel.DataAnnotations;
namespace veic_web.Models
{
public class Product
{
[Key]
public int Id { get; set; }
public int Param_id { get; set; }
public int Statu_id { get; set; }
public int Lang_id { get; set; }
public int Img_id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
}
}
Db Context
Solution Explorer
Model右键点击Add-》New Item选择Class Name: ApplicationDbContext.cs
添加引用:
using Microsoft.EntityFrameworkCore;
添加继承:DbContext;
and “Generate Constructor ‘ApplicationDbContext(options)’"(shortcut: Ctrl+. or Alt+Enter)
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
代码模板在DbContext.cs 添加Entity类支持
public DbSet<Product> Products
{
get; set;
}
操作类
- 接口:
Solution Explorer -》 Model右键点击Add-》New Item选择Interface
Name: IProductRepository.cs
public interface IProductRepository
{
IQueryable<Product> Products { get; }
}
- 实现:
Solution Explorer -》 Model右键点击Add-》New Item选择Class
Name: EFProductRepository.cs
public class EFProductRepository(ApplicationDbContext context) : IProductRepository
{
public IQueryable<Product> Products => context.Products;
}
connector
Project-》Manager NuGet Packages
connection string
- appsettings.json
"Data": {
"VeicWeb": {
"ConnectionString": "server=127.0.0.1; user id=DBAdmin; password=xbfirst; database=carnumber; pooling=false; Convert Zero Datetime=True;"
}
},
前后代码比较:

DI - Configure Services
Program.cs
- 数据库context
//// MySql - Oracle
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySQL(builder.Configuration["Data:VeicWeb:ConnectionString"]));
- Repository
builder.Services.AddTransient<IProductRepository, EFProductRepository>();
前后代码比较:

View-Controller
Index.cshtml:
@model IEnumerable<Product>
@foreach (var p in Model)
{
<div>
<h3>@p.Name</h3>
@p.Description
</div>
}
前后代码比较:

Controller
HomeController.cs
- 引用实例:
private readonly IProductRepository _productRepository;
public HomeController(ILogger<HomeController> logger, IProductRepository productRepository)
{
_logger = logger;
_productRepository = productRepository;
}
- 调用他:
public IActionResult Index()
{
return View(_productRepository.Products);
}
前后代码比较:


