1、添加引用Nuget包
Microsoft.EntityFrameworkCore.Sqlite Microsoft.EntityFrameworkCore.Design Microsoft.EntityFrameworkCore.Tools.DotNet
2、創建數據庫上下文
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace ConsoleApp.SQLite
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=blogging.db");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
Startup里注入:
services.AddDbContext<BloggingContext>();
3、數據庫遷移
dotnet ef migrations add InitialCreate //提交到數據庫 dotnet ef database update
4、發布
這里僅說一下注意事項,我們在開發調試的時候,默認生成的數據庫文件所在目錄為:
bin/Debug/netcoreapp1.1/blogging.db
發布后,應該把數據庫文件拷貝到發布程序的根目錄里,不然報錯,找不到數據庫文件。
參考文獻:https://docs.microsoft.com/zh-cn/ef/core/get-started/netcore/new-db-sqlite
