NET Core添加 Sqlite 数据库

相关文章回顾

.net framework 命令行项目使用 sqlite,DbContext

C# .NET EF框架 webapi 安装使用sqlite

visual studio 2022,ADO.NET 实体数据模型添加 sqlite数据库对象

Sqlite安装

环境说明

  • Visual Studio 2022
  • .NET Core 6.0

在这里插入图片描述

Nuget安装

  • Microsoft.EntityFrameworkCore.Sqlite
  • Microsoft.EntityFrameworkCore.Sqlite.Core
  • Newtonsoft.Json
    在这里插入图片描述

测试程序

在这里插入图片描述
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!");

测试结果

在这里插入图片描述

结尾

Sqlite3是个特别好的本地数据库,体积小,无需安装,是写小控制台程序最佳数据库。NET Core是.NET 未来的方向,我也最近打算把技术栈慢慢往那边迁移。

猜你喜欢

转载自blog.csdn.net/qq_44695769/article/details/131311614
今日推荐