5

Web重温系列(二):SQLite+EF6实现本地化存储

 3 years ago
source link: https://www.cnblogs.com/ceachy/p/SQLite_And_EF6.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Web重温系列(二):SQLite+EF6实现本地化存储

  本来我们的产品有着复杂的层次结构,作为客户端的C# WinForm是不操作数据库的。但是最近有个需求,需要将数据本地保存。可选的方案很多,比如文本文件或者XML序列化和反序列化,或者如access、dbf等传统文件数据库。但是为了赶时髦,我们决定使用SQLite(其实也不时髦了:))。而且我们既然不习惯于操作数据库,我们就不想使用基本的ADO.Net写SQL语句来操作数据,于是ORM就是最好的选择了。EF是微软的实现,对于首次尝试ORM的我们,当然是第一选择。

  领导和同事给了很多指导和帮助,在此表示感谢。

  操作流程如下:

  1. 安装SQLite客户端

    客户端种类繁多,笛子安装的是DB Browser for SQLite(http://sqlitebrowser.org/);

  2. 创建数据库(文件)和数据表

    a. 利用客户端创建数据库文件(扩展名为.sqlite),一个数据库文件相当于一个database(单数据库);

    b. 执行创建数据库表Student的脚本(相当于表级别);

  3. 在VS中利用NuGet包管理器安装System.Data.SQLite

    会自动引用控件和修改App.config配置文件;

  4. 创建于表结构完全一样的类

  也可以不一样,然后通过Annotation标签,Table、Key、Column等映射到SQLite表中

  (也可以通过创建“ADO.Net数据模型实体”来自动生成,如果采取这种方式,5也不需要了)

[Table("Student")]
public class  Student
{
  [Key]
  [Column("id")]
  public int Id {get;set;}
  [Column("name")]
  public string Name {get;set;}
  [Column("age")]
  public decimal Age {get;set;}
}

  5. 创建自己的DbContext类

    需要继承自DbContext类(相当于database),和DbSet属性 (相当于表的行集)

public class StudentDbContext  : DbContext
{
    public StudentDbContext()
            : base("name=connectionName")
        {
        }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Student>  Students { get; set; }
    
}

  6. 表的增删查改

StudentDbContext  db = new StudentDbContext ();
var student = new Student()
{
    Id = 1,
    Name = "Luke",
    Age = 18,
};

db.Students.Add(student);

db.SaveChanges();

db.Students.Remove(student);

db.SaveChanges();

db.Students.Load();

var row = db.Students.Find(1);

row.Name = "改了改了";

db.SaveChanges();

  此外,学习EntityFramework,Entity Framework Tutorial这个 英文网站不错。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK