.NET 通过ORM操作SQLite

简介

本篇是.net 中 使用 SQLite(普通版)( https://blog.csdn.net/qq_23219257/article/details/132171167) 的进阶篇。
在现代软件开发中,使用数据库是不可或缺的一部分。对于.NET开发者来说,SQLite是一种常用的轻量级关系型数据库。为了更方便地与数据库进行交互,开发者通常使用ORM(对象关系映射)工具。本文将介绍在.NET平台上如何使用ORM操作SQLite数据库,以实现轻便快捷的使用SQLite。

什么是ORM?

ORM是一种现代编程技术,可认为是中间件,用于将对象模型与关系型数据库之间建立映射关系。通过ORM,开发者可以使用面向对象的方式操作数据库,而无需编写复杂的SQL语句。

为什么使用SQLite?

SQLite是一种轻量级的嵌入式数据库,其特点是小巧、快速和可靠。对于需要在应用程序中集成数据库功能的.NET开发者来说,SQLite是一个理想的选择,尤其是需要本地数据的支持的情况下,SQLite是优先选择的,当然也有自定义数据的,需要根据实际情况来取舍的。

选择适当的ORM工具

在.NET平台上,有许多优秀的ORM工具可供选择,如Entity Framework、Dapper和NHibernate等。根据项目需求和开发者的偏好,选择合适的ORM工具是非常重要的,本篇用EF来制作,有兴趣的可以试试其它方案。

使用Entity Framework进行ORM操作SQLite

步骤1:安装Entity Framework

首先,我们需要在Visual Studio中安装Entity Framework。可以通过NuGet包管理器来安装Entity Framework。

步骤2:创建数据模型

接下来,我们需要根据数据库结构创建数据模型。可以使用代码优先或数据库优先两种方式创建数据模型。

代码优先

如果选择代码优先方式,可以通过编写实体类来定义数据模型。Entity Framework会根据实体类的属性和关系自动生成数据库结构。

数据库优先

如果选择数据库优先方式,可以使用Entity Framework的逆向工程功能自动生成实体类。只需提供SQLite数据库连接字符串,Entity Framework将根据数据库结构生成实体类。

相关的数据模型参考

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LocalArticle.Model
{
class CodeType
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = “类型id”)]
public string code_type_id { get; set; }
public string parent_id { get; set; }
public string order_id { get; set; }
public string type { get; set; }
public string isdel { get; set; }
}
}

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LocalArticle.Model
{
class Code
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string code_id { get; set; }
public string code_type_id { get; set; }
[ForeignKey(“code_type_id”)]
public CodeType CodeType { get; set; }
public string title { get; set; }
public string code_content_id { get; set; }
[ForeignKey(“code_content_id”)]
public CodeContent CodeContent { get; set; }
[Display(Name = “创建时间”)] public DateTime createtime { get; set; }
[Display(Name = “修改时间”)] public DateTime updatetime { get; set; }
}
}
每个数据模型有对应的数据表,其它的数据表有对应的数据模型。

步骤3:执行CRUD操作

一旦创建了数据模型,就可以使用Entity Framework来执行CRUD(增删改查)操作。以下是一些常见的操作示例:

查询数据
private void searchBtn_Click(object sender, EventArgs e)
{
this.code_id = "";
this.selectedIndex = -1;
      
using (AppDbContext db = new AppDbContext())
{
    var model = db.code.Where(s => !s.code_id.Equals("1"));
    if (this.typeComboBox.SelectedIndex != -1)
    {
        string code_type_id = this.typeComboBox.SelectedValue.ToString();
        model = model.Where(m => m.code_type_id.Equals(this.typeComboBox.SelectedValue));
    }
    if (!string.IsNullOrEmpty(this.keywordTextBox.Text))
    {
        model = model.Where(m => m.title.Contains(this.keywordTextBox.Text));
    }
    UiDataS.Instance.LoadDataForListBox(this.titleListBox, model.ToList());

    this.searchBtn.Text = "搜索";
}
}
插入数据
private async void addBtn_Click(object sender, EventArgs e)
{
 if (string.IsNullOrEmpty(this.typeComboBoxForAdd.Text) || this.typeComboBoxForAdd.SelectedIndex == -1)
 {
     MessageBox.Show("请选择分类(如果没有分类,请先添加)");
     ShowCodeTypeForm();
     return;
 }

 if (string.IsNullOrEmpty(this.titleTextBoxForAdd.Text))
 {
     MessageBox.Show("请输入标题");
     return;
 }
 if (string.IsNullOrEmpty(this.contentRichTextBoxForAdd.Text))
 {
     MessageBox.Show("请输入记事内容");
     return;
 }

 using (AppDbContext db = new AppDbContext())
 {
     Code model = new Code();
     model.code_type_id = this.typeComboBoxForAdd.SelectedValue.ToString();
     model.title = this.titleTextBoxForAdd.Text;
     model.createtime = DateTime.Now;
     model.updatetime = DateTime.Now;
     model.CodeContent = new CodeContent();
     model.code_content_id = model.CodeContent.code_content_id;
     await db.code.AddAsync(model);
     code_id = model.code_id;
     string pathParent = DataS.Instance.UserReposPath + model.createtime.Year;
     if (!Directory.Exists(pathParent))
     {
         Directory.CreateDirectory(pathParent);
     }
     //还是得需要扩展名的,需要存储在lfs空间上(内容不要站用code的空间)
     string path = pathParent + "\\" + model.code_content_id + ".rtf";
     File.WriteAllText(path, this.contentRichTextBoxForAdd.Text);
     this.contentRichTextBoxForAdd.SaveFile(path, RichTextBoxStreamType.RichText);
     model.CodeContent.content = model.createtime.Year + "\\" + model.code_content_id + ".rtf";
     await db.SaveChangesAsync();
     sum++;
     this.Text = "记事(有则用,无则加):" + sum;
 }
 this.titleTextBoxForAdd.Text = "";
 this.contentRichTextBoxForAdd.Text = "";
}
更新数据
private async void saveForEdit_Click(object sender, EventArgs e)
{
 if (this.typeComboBoxForEdit.SelectedIndex == -1)
 {
     MessageBox.Show("请选择类型");
     return;

 }
 if (string.IsNullOrEmpty(this.titleTextBoxForEdit.Text))
 {
     MessageBox.Show("请输入标题");
     return;
 }
 if (string.IsNullOrEmpty(this.contentRichTextBoxForEdit.Text))
 {
     MessageBox.Show("请输入记事内容");
     return;
 }
 using (AppDbContext db = new AppDbContext())
 {
     var model = await db.code.Include(m => m.CodeContent).FirstOrDefaultAsync(m => m.code_id.Equals(code_id));
     if (model == null)
     {
         MessageBox.Show("没有找到相应的记录,请核查");
         return;
     }
     model.updatetime = DateTime.Now;
     model.code_type_id = this.typeComboBoxForEdit.SelectedValue.ToString();
     model.title = this.titleTextBoxForEdit.Text;
     FileInfo fileInfo = new FileInfo(DataS.Instance.UserReposPath + model.CodeContent.content);
     if (!fileInfo.Exists)
     {
         Directory.CreateDirectory(fileInfo.Directory.ToString());
     }
     this.contentRichTextBoxForEdit.SaveFile(fileInfo.FullName, RichTextBoxStreamType.RichText);
     db.code.Update(model);
     await db.SaveChangesAsync();
 }
}
删除数据

一般情况下,不会采用物理删除的方式,来删除数据,会采用逻辑删除,这个和上面更新数据是一样的操作,就不在赘述了。

总结

通过使用ORM工具,如EF,开发者可以更方便地在.NET平台上操作数据库。ORM提供了一种简化数据库交互的方式,使开发过程更加高效和便捷。无论是查询、插入、更新还是删除数据,ORM工具都能提供强大的支持。因此,掌握并善用ORM工具对于.NET开发者来说是非常重要的技能。

其它阅读

.net 中 使用 sqlite(普通版)
本地分类记事1.2.7

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值