使用 EF Core 处理Sqlite数据库
1.通过NuGet安装Microsoft.EntityFrameworkCore.Sqlite
2.编写生成数据库的实体类
因为EF Core是通过实体类来作为数据库的字段
public class User
{
/// <summary>
/// 主键 Id
/// </summary>
[Key]
public int Id { get; set; }
/// <summary>
/// 数据库 Name
/// </summary>
[Column("Name")]
public string Name { get; set; }
/// <summary>
/// 数据库 Sex
/// </summary>
[Column("Sex")]
public string Sex { get; set; }
}
3.编写EF Core的实体类
public class AppDbContext : DbContext
{
private readonly string _connection;
//实体表,提供给外部crud使用,PersonInfos内部有DataContext 的实例
public DbSet<User> User { get; set; }
public AppDbContext()
{
//1、获取连接数据库的字符串
_connection = ConfigurationManager.ConnectionStrings["SqliteEF6ConnectionStr"].ConnectionString;
}
//2、联接数据库
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlite(_connection);
}
//3、建立实体和数据库表格 一 一 映射。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("User").HasKey(b => b.Id);
}
}
4.创建数据库语句及增删改查
/// <summary>
/// 创建数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
AppDbContext dbContext = new AppDbContext();
dbContext.Database.EnsureCreated();
}
/// <summary>
/// 增加数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
AppDbContext dbContext = new AppDbContext();
User user = new User();
user.Name = "Test";
user.Id = 1;
user.Sex = "男";
dbContext.Add(user);
User user2 = new User();
user2.Name = "Test";
user2.Id = 3;
user2.Sex = "男";
dbContext.Add(user2);
dbContext.SaveChanges();
}
/// <summary>
/// 修改数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
AppDbContext dbContext = new AppDbContext();
User? user = dbContext.User.Where(b => b.Id == 3).FirstOrDefault();
user.Sex = "女";
dbContext.SaveChanges();
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
AppDbContext dbContext = new AppDbContext();
User? user = dbContext.User.Where(b => b.Id == 3).FirstOrDefault();
dbContext.Remove(user);
dbContext.SaveChanges();
}
/// <summary>
/// 查询数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
AppDbContext dbContext = new AppDbContext();
List<User> users = dbContext.User.ToList();
}
5.总结
EF Core
优点:
微软官方ORM
功能强大,支持模式多
文档齐全
缺点:
1.复杂查询生成的SQL语句性能太差(对操作功力要求高)
2.一些常用功能缺失,需要自已封装
3.批量操作性能不算太好
4.原生SQL支持不友好 ,需要自己封装
使用EF Core最好的方法就是结合其他的sql框架一起使用
2022/12/8