文章目录
1.基础配置
1.1 Nuget 引用
- EntityFramework
- System.Data.SQLite
- SQLite.CodeFirst
1.2 配置文件
引用Nuget 后在App.config 中添加sqlite db 的链接字符串
添加的配置文件
<connectionStrings>
<add name="localdb" connectionString="data source=.\db\localdb.db;Version=3;foreign keys=true" providerName="System.Data.SQLite" />
</connectionStrings>
<!--添加 provider-->
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
2 CodeFist 代码
2.1 实体创建
public class LocalPerson
{
[Key]//主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]//ID 自增长
public int ID { get; set; }
public string Name { get; set; }
public int Sex { get; set; }
}
2.2 数据库初始化数据库重写
public class LocalDbInitializer : SqliteDropCreateDatabaseWhenModelChanges<SqliteDBContext>
{
public LocalDbInitializer(DbModelBuilder modelBuilder) : base(modelBuilder)
{
}
protected override void Seed(SqliteDBContext context)
{
//初始参数
context.LocalPerson.Add(new Entity.LocalPerson
{
Name = "初始化测试",
Sex = 1
});
context.SaveChanges();
base.Seed(context);
}
}
2.3 数据库上下文 SqliteDBContext
public class SqliteDBContext : DbContext
{
public SqliteDBContext() : base("name = localdb")
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
Database.SetInitializer(new LocalDbInitializer(modelBuilder));
}
public DbSet<LocalPerson> LocalPerson { get; set; }
}
2.4 EF 调用代码
using (var db = new SqliteDBContext())
{
//查看初始化数据
Console.WriteLine(db.LocalPerson.ToList().ToJson());
//添加数据
db.LocalPerson.Add(new LocalPerson()
{
Name = "测试添加",
Sex = 2
});
db.SaveChanges();
//查看总数据
Console.WriteLine(db.LocalPerson.ToList().ToJson());
}
执行结果:
至此C#Sqlite EntityFramework CodeFist 的使用已完成
本文代码已上传:https://download.csdn.net/download/johnson55925/10789217
项目开源地址:
https://gitee.com/fcode_me/FCODE_DEMO