Netcore 基础学习
Ef Core 快速开始实例
创建一个空的web api 项目
添加 Pomelo.EntityFrameworkCore.Mysql 的nuget包引用
创建实体
创建DbContext
配置连接字符串并且注入DbContext
使用DbContext完成数据查询与插入
步骤一
创建 netcore Api 项目
进入vs 创建一个空的API 项目文件
创建Date 文件夹, 让后创建Progame 文件夹,在Progame文件夹下创建 实体类,创建五个实体类
Assistant
namespace Progect.Data.Project
{
public class Assistant : Entity
{
public string MemberId { get; set; }
public string ProjectGroupId { get; set;}
}
}
Member
namespace Progect.Data.Project
{
public class Member:Entity
{
public string UserId { get; set; }
public string Progress { get; set; }
public string ProjectId { get; set; }
}
}
Progect
namespace Progect.Data.Project
{
public class Project:Entity
{
public string Title { get; set; }
public string Superviosr { get; set; }
public string StartData { get; set; }
public string EndDate { get; set; }
public string PlanId{ get; set; }
}
}
ProjectGroup
namespace Progect.Data.Project
{
public class ProjectGroup:Entity
{
public string Name { get; set; }
public string ProjectId { get; set; }
}
}
Task
namespace Progect.Data.Project
{
public class Task:Entity
{
public string Title { get; set; }
public string SectionId { get; set; }
public string Desription { get; set; }
public string ProjectId { get; set; }
public string MemberId { get; set; }
public EnumTaskStatus Staus { get; set; }
}
}
所有的 类 都继承一个 Entity 的通用类
public class Entity
{
public string Id { get; set; }
public string IdentityId { get; set; }
public string UserId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime CreatedAt { get; set; }
public string CreatedBy { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime LastUpdatedAt { get; set; }
public DateTime LastupdatedBy { get; set; }
}
建立 DBcontext ,用来连接数据库
这个类 在Data 文件夹下
using Microsoft.EntityFrameworkCore;//引用entityframewokcoe 库
public class LighterDbContext : DbContext
{
public LighterDbContext(DbContextOptions<LighterDbContext> options) : base(options)
{
}
//DBse project 文件夹 下的 所有属性类
public DbSet<Project.Project> Projects { get; set; }
public DbSet<Project.Member> Members { get; set; }
public DbSet<Project.Assistant> Assistants { get; set; }
public DbSet<Project.ProjectGroup> ProjectGroups { get; set; }
public DbSet<Project.Task> Tasks { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Project.Project>()
.Property(p => p.Id).ValueGeneratedOnAdd();
base.OnModelCreating(modelBuilder);
}
}
配置连接字符串并注入到Dbcontext 里面,在APPsettings.json 里面添加
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
// 注意不要打错
"ConnectionStrings": {
"LighterDbContext": "server=172.22.227.14;port=6306;user=root; password=root123456;database=ubuntu"
},
"AllowedHosts": "*"
}
straup 里面添加路由
// 把 configuation 通过构造函数注入到start up
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// 添加连接字符串
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
services.AddDbContext<LighterDbContext>(options =>
{
options.UseMySql(Configuration.GetConnectionString("LighterDbContext"));
});
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
初始化数据库
通过 命令行工具 进入到项目下面
// 安装dotnet tool ef工具
dotnet tool install --global dotnet-ef
// 以下命令需要在api项目的目录下执行
// 在项目内安装
dotnet add package Microsoft.EntityFrameworkCore.Design
//添加迁移文件
dotnet ef migrations add Init
添加迁移文件的时候会报很多错误, 注意看报错原因,然后一个个排查,要有耐心,不要看到很多就放弃掉
// 更新数据库
dotnet ef database update
迁移成功后, 会在项目上面出现一个migrations 的文件夹
创建 programeController
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Progect.Data;
using System.Threading;
using Progect.Data.Project;
using Microsoft.EntityFrameworkCore;
using System.Net;
namespace Progect.Controller
{
[ApiController]
[Route("api/[controller]")]
public class ProjectController : ControllerBase
{
//把DBcontext 通过构造函数注入到这里
private readonly LighterDbContext _lighterDbContext;
public ProjectController(LighterDbContext lighterDbContext)
{
_lighterDbContext = lighterDbContext;
}
//查询projects 表里的数据
[HttpGet]
public async Task<ActionResult<IEnumerable<Project>>> GetListAsync(CancellationToken cancellationToken)
{
return await _lighterDbContext.Projects.ToListAsync(cancellationToken);
}
// 创建一条数据
[HttpPost]
public async Task<ActionResult<IEnumerable<Project>>> CreateAsync([FromBody]Project project,CancellationToken cancellationToken)
{
project.Id = Guid.NewGuid().ToString();
_lighterDbContext.Projects.Add(project);
await _lighterDbContext.SaveChangesAsync(cancellationToken);
return StatusCode((int)HttpStatusCode.Created, project);
}
}
}

浙公网安备 33010602011771号