Article directory
Related Article Review
The .net framework command line project uses sqlite, DbContext
C# .NET EF framework webapi installation using sqlite
Visual studio 2022, ADO.NET entity data model adds sqlite database objects
SQLite installation
Environmental description
- Visual Studio 2022
- .NET Core 6.0
Nuget installation
- Microsoft.EntityFrameworkCore.Sqlite
- Microsoft.EntityFrameworkCore.Sqlite.Core
- Newtonsoft.Json
test program
ORMContext
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqliteTest2.DB
{
//继承DbContext,让EF接管
public class ORMContext : DbContext
{
public DbSet<Student> Students {
get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//数据库连接字符串
optionsBuilder.UseSqlite("Data Source=blogging.db");
}
}
//测试类
public class Student
{
[Key]//主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]//自动递增
public int Id {
get; set; }
public string Name {
get; set; }
public int Age {
get; set; }
public string Sex {
get; set; }
}
}
Program.cs
// See https://aka.ms/new-console-template for more information
using Newtonsoft.Json;
using SqliteTest2.DB;
ORMContext _ORMContext = new ORMContext();
//如果没有数据库,则自动创建
_ORMContext.Database.EnsureCreated();
for(var i = 0;i < 10; i++)
{
_ORMContext.Students.Add(new Student()
{
Name = "Laly" + i,
Age = i,
Sex = "女"
});
}
//保存数据库更新
_ORMContext.SaveChanges();
//打印数据
var res = _ORMContext.Students.Where(t => t.Sex == "女").ToList();
Console.WriteLine(JsonConvert.SerializeObject(res));
Console.WriteLine("Hello, World!");
Test Results
end
Sqlite3 is a particularly good local database with small size and no installation required. It is the best database for writing small console programs. NET Core is the future direction of .NET, and I plan to slowly migrate the technology stack there recently.