EF6-SQLite-CodeFirst P1

发布于:2021-10-16 22:15:37



EF6-SQLite-CodeFirst P1
入门篇,框架搭建,初始化1.安装System.Data.SQLite2.创建实体类3.创建上下文类3.1 通过App.config指定连接字符串3.2 通过传入灵活的连接字符串
4.安装SQLite.CodeFirst5.测试6.查看数据库存储



入门篇,框架搭建,初始化

本文指在快速入门该框架,相当于学一门新语言然后输出“Hello World!”


1.安装System.Data.SQLite

安装以下包:

预览更改:


2.创建实体类

public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
public Grade Grade { get; set; }//年级
}

public class Grade
{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
public ICollection Students { get; set; }
}

3.创建上下文类

创建上下文有两种方式


3.1 通过App.config指定连接字符串

通过在App.config正常配置连接字符串,此方式适合数据库固定位置






假设上下文类为StudentContext,那么该类的构造函数应该是这样:


public StudentContext():base("SchoolSqlite")
{
public DbSet Students { get; set; }
}

3.2 通过传入灵活的连接字符串

顾名思义,可以通过程序外部传入连接字符串初始化DbContext类。


需要使用以下DbContext的构造方法:


public DbContext(DbConnection existingConnection, bool contextOwnsConnection);

假设上下文类为StudentContext,那么该类的构造函数应该是下方代码所示:



备注:
SQLiteProviderFactory需引用System.Data.SQLite.EF6
DbConnection需引用System.Data.Common



static string dbPath = "Data Source=Data Source=|DataDirectory|\Data\SchoolSqlite.db3";
public static StudentContext Instance
{
get
{
DbConnection sqliteCon = SQLiteProviderFactory.Instance.CreateConnection();
sqliteCon.ConnectionString = dbPath;
return new StudentContext(sqliteCon);
}
}
private StudentContext(DbConnection con) : base(con, true) { }
public DbSet Students { get; set; }

4.安装SQLite.CodeFirst

因为本地不存在数据库时,需要用代码自动创建新数据库,所以需要安装



在上下文类中重写OnModelCreating方法



备注:需引用using SQLite.CodeFirst



public class StudentContext : DbContext
{

//public StudentContext() : base("SchoolSqlite")
//{

//}
static string dbPath = "Data Source=|DataDirectory|\Data\SchoolSqlite.db3";
public static StudentContext Instance
{
get
{
DbConnection sqliteCon = SQLiteProviderFactory.Instance.CreateConnection();
sqliteCon.ConnectionString = dbPath;
return new StudentContext(sqliteCon);
}
}
private StudentContext(DbConnection con) : base(con, true) { }
public DbSet Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new SqliteCreateDatabaseIfNotExists(modelBuilder));
}
}

5.测试

最后配置App.config,在标签中添加以下代码:




实际添加效果如下:


添加一个按钮,测试:


private void btn_Init_Click(object sender, EventArgs e)
{
var cxt = new StudentContext();
var Zhangsan = new Student() { Name = "张三", Age = 25 };
cxt.Students.Add(Zhangsan);
cxt.SaveChanges();
MessageBox.Show("初始化完毕!");
}

6.查看数据库存储


源代码及文档地址:


    CSDN下载.蓝奏云

相关推荐

最新更新

猜你喜欢