• .Net Core EF Core之Sqlite使用
  • 发布于 2个月前
  • 80 热度
    0 评论
SQLite是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。它是一个零配置的数据库,这意味着与其他数据库不一样,您不需要在系统中配置。就像其他数据库,SQLite 引擎不是一个独立的进程,可以按应用程序需求进行静态或动态连接。SQLite 直接访问其存储文件。
下面介绍下在.Net Core EF Core之Sqlite使用
1、添加引用Nuget包
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Design
 
Microsoft.EntityFrameworkCore.Tools.DotNet
2、创建数据库上下文
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
 // 堆代码 duidaima.com
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://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite
https://github.com/dotnet/efcore/tree/main/test/EFCore.Sqlite.Tests
用户评论