添加实体模型
在项目根目录下新建Models
文件夹,在这里可以创建实体类
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EFGetStarted.Models
{
public class Company
{
[Key] //主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增
public int Id { get; set; }
[Required] // 非空
[Column(TypeName = "varchar(200)")] // 设置字段类型
[Comment("公司名称")] // 列注释
public string CompanyName { get; set; }
// 创建时间
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Inserted { get; set; }
// 插入或更新时间
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime LastUpdated { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EFGetStarted.Models
{
public class Employee
{
[Key] //主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增
public int Id { get; set; }
[Required] // 非空
[Column(TypeName = "varchar(200)")] // 设置字段类型
[Comment("员工姓名")] // 列注释
public string Name { get; set; }
[Required] // 非空
[Comment("性别")] // 列注释
public bool Sex { get; set; }
[ForeignKey("company")] //外键
public int CompanyId { get; set; }
public Company company { get; set; }
// 创建时间
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Inserted { get; set; }
// 插入或更新时间
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime LastUpdated { get; set; }
}
}
添加数据库上下文
新建Data
文件夹,在其中添加数据库上下文
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
在数据库上下文中注册模型
using EFGetStarted.Models;
using Microsoft.EntityFrameworkCore;
namespace EFGetStarted.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Company> companies { get; set; }
public DbSet<Employee> employees { get; set; }
}
}
配置数据库
在appsettings.json
添加如下内容
"ConnectionStrings": {
"MysqlConnection": "Data Source=127.0.0.1;Database=ef-mysql-api;User ID=root;Password=123456789;pooling=true;port=3306;sslmode=none;CharSet=utf8;"
},
修改Startup.cs
// 将服务添加到DI容器中
public void ConfigureServices(IServiceCollection services)
{
// 读取数据库连接字符串
var connection = Configuration.GetConnectionString("MysqlConnection");
// 注册数据库上下文
services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(connection));
services.AddControllers();
}
迁移数据库
在Powershell
中执行
dotnet ef migrations add first
使用如下命令将表结构同步到数据库
dotnet ef database update
添加Service层
在项目根目录下新建Service
文件夹,在这里可以创建Service类
新建CompanyService
类
using EFGetStarted.Data;
using EFGetStarted.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EFGetStarted.Services
{
public class CompanyService
{
public ApplicationDbContext Context;
public CompanyService(ApplicationDbContext context)
{
Context = context;
}
public async Task<List<Company>> GetCompanys()
{
var companys = await Context.companies.ToListAsync();
return companys;
}
}
}
在DI容器中注册该Service
// 将服务添加到DI容器中
public void ConfigureServices(IServiceCollection services)
{
// 读取数据库连接字符串
var connection = Configuration.GetConnectionString("MysqlConnection");
// 注册数据库上下文
services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(connection));
// 注册Service
services.AddScoped<CompanyService>();
services.AddControllers();
}
新建Controller层
在项目根目录下新建Controller
文件夹,在这里可以创建Controller类
新建CompaniesController
类
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using EFGetStarted.Models;
using EFGetStarted.Services;
using System.Threading.Tasks;
namespace EFGetStarted.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CompaniesController : ControllerBase
{
private readonly CompanyService _companyService;
public CompaniesController(CompanyService companyService)
{
_companyService = companyService;
}
// GET: api/Companies
[HttpGet]
public async Task<ActionResult<IEnumerable<Company>>> Getcompanies()
{
return await _companyService.GetCompanys();
}
}
}
访问https://localhost:5001/api/Companies
即可