创建数据库

创建文件夹

./Context

创建文件

./Context/BaseEnity.cs

./Context/Memo.cs

./Context/MyTodoContext.cs

./Context/Todo.cs

./Context/User.cs

创建数据对象

  • ./Context/BaseEnity.cs

    namespace MyToDo.Api.Context{public class BaseEnity{public int Id { get; set; }public DateTime CreateDate { get; set; }public DateTime UpdateDate { get; set; }}}
  • ./Context/Memo.cs

    namespace MyToDo.Api.Context{public class Memo:BaseEnity{public string Title { get; set; }public string Content { get; set; }}}
  • ./Context/MyTodoContext.cs

    创建数据库DbSet

    using Microsoft.EntityFrameworkCore;namespace MyToDo.Api.Context{public class MyTodoContext:DbContext{public MyTodoContext(DbContextOptions options) : base(options) { }public DbSet TodoSet { get; set; }public DbSet UserSet { get; set; }public DbSet MemoSet { get; set; }}}
  • ./Context/Todo.cs

    namespace MyToDo.Api.Context{public class Todo:BaseEnity{public string Title { get; set; }public string Content { get; set; }public int Status { get; set; }}}
  • ./Context/User.cs

    namespace MyToDo.Api.Context{public class User:BaseEnity{public string Account { get; set; } public string UserName { get; set; }public string Password { get; set; }}}

添加nuget包

  • Microsoft.EntityFrameworkCore.Design

    Shared design-time components for Entity Framework Core tools.

  • Microsoft.EntityFrameworkCore.Sqlite

    SQLite database provider for Entity Framework Core.

  • Microsoft.EntityFrameworkCore.Tools

    Entity Framework Core Tools for the NuGet Package Manager Console in Visual Studio.

    Enables these commonly used commands:
    Add-Migration
    Bundle-Migration
    Drop-Database
    Get-DbContext
    Get-Migration
    Optimize-DbContext
    Remove-Migration
    Scaffold-DbContext
    Script-Migration
    Update-Database

配置连接字符串

  • appsettings.json
{"ConnectionStrings": {"TodoConnection": "Data Source=todo.db"},"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*"}

配置数据库连接选项

  • program.cs
builder.Services.AddDbContext(option =>{var constr = builder.Configuration.GetSection("ConnectionStrings")["TodoConnection"];option.UseSqlite(constr);});var app = builder.Build();

启动配置数据库

[工具]-> [Nuget包管理器]-> [程序包管理器控制台]

  1. 输入 :Add-Migration mytodo

    生成数据库配置项文件

  2. 输入 :Update-Database

    将数据库更新到sqlite数据库中,制成sqlite数据库文件