- 安装nuget包
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Sqlite
尽量选用与项目sdk相近的包
- 新建实体
[Table("list")]
public class TbList
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("name")]
public string Name { get; set; }
}
- 新建数据库上下文类
public class TestDbContext : DbContext
{
public DbSet<TbList> TbLists { get; set; }
private readonly string _connStr;
public TestDbContext(string connStr)
{
_connStr = connStr;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(_connStr);
}
}
- 使用
using var context = new TestDbContext(@"Data Source=D:\sqlite\menu.db");
var data = context.TbLists.ToList();
5.如果需要注入,在Startup.cs中ConfigureServices方法添加下面代码
services.AddDbContext<MyDbContext>(
options => options.UseSqlite(Configuration.GetConnectionString("sqlite")));
6.官网地址