1.安装依赖
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
2.添加appsettings.json(DB路径使用了绝对路径)
{ "exclude": [ "**/bin", "**/bower_components", "**/jspm_packages", "**/node_modules", "**/obj", "**/platforms" ], "ConnectionStrings": { "db": "Data Source=C:\Users\lixipeng\source\repos\ConsoleApp1\ConsoleApp4\db/blogging.db" } }
3.使用CodeFirst
3.1 新建Models文件夹
3.2新建Blog类
using System; using System.Collections.Generic; using System.Text; namespace Sqlite.Models { public class Blog { public int BlogId { get; set; } public string Url { get; set; } public ICollection<Post> Posts { get; set; } } }
3.3新建Post类
using System; using System.Collections.Generic; using System.Text; namespace Sqlite.Models { 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; } } }
3.4新建数据库上下文
using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Sqlite.Models { public class BloggingContext:DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Blog> Blogs { get; set; } private IConfiguration configuration; public BloggingContext() { configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite(configuration.GetConnectionString("db")); } } }
4新建db文件夹
5生成数据库(用命令生成失败了,不知是不是我环境的问题,改用了代码生成数据库(生成数据库后应该需要注释掉)),运行代码后会在设置的文件夹中生成db文件
using Sqlite.Models; using System; using System.Linq; namespace ConsoleApp4 { class Program { static void Main(string[] args) { using (BloggingContext db = new BloggingContext()) { db.Database.EnsureCreated();//这句代码会创建数据库,需要注意数据库路径 } } } }
6插入数据保存和查询测试
using Sqlite.Models; using System; using System.Linq; namespace ConsoleApp4 { class Program { static void Main(string[] args) { using (BloggingContext db = new BloggingContext()) { db.Database.EnsureCreated(); //这句代码会创建数据库,需要注意数据库路径(创建后自己记得注释) db.Blogs.Add(new Blog { Url = "https://blog.csdn.net/lms99251" }); var count = db.SaveChanges(); var fir = db.Blogs.ToList(); Console.WriteLine(db.Blogs.FirstOrDefault().BlogId); } } } }