1. 程式人生 > 其它 >Asp.Net Core API +EF+Sqllite+Automapper+搭建後端服務 系列(二)通過Code Frist建立資料庫

Asp.Net Core API +EF+Sqllite+Automapper+搭建後端服務 系列(二)通過Code Frist建立資料庫

1、安裝Nuget包

Entity Framework Core

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Sqlite

Microsoft.EntityFrameworkCore.Tools

2、建立遷移檔案 生成資料庫

建立model資料夾 建立Todo類 BaseModel類

 public class Todo:BaseModel 
    {
        public string Title { get; set; }
        public string Content { get
; set; } public int Status { get; set; } }
 public class BaseModel
    {
        public int ID { get; set; }
        public DateTime Createtime { get; set; }
        public DateTime Updatetime { get; set; }
    }

建立MyContext類

    public class MyContext : DbContext
    {
        public
MyContext(DbContextOptions<MyContext> options) : base(options) { } public DbSet<Todo> Todo { get; set; } }

配置資料庫連線,修改appsettings.josn配置檔案 增加ConnectionStrings

{
  "ConnectionStrings": {"testConnection": "Data Source=Test.db"},
  "Logging": {
    "LogLevel": {
      
"Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }

修改Startup類 在public void ConfigureServices(IServiceCollection services) 方法中加入以下程式碼

 //配置資料庫連線
            services.AddDbContext<MyToDoContext>(options =>
            {
                var connection = Configuration.GetConnectionString("TodoConnection");
                options.UseSqlite(connection);
            });

在程式包管理器控制檯輸入Add-Migration MyApi 然後回車 建立遷移檔案,建立成功後會增加2個檔案

輸入Update-Database 建立資料庫