HarmonyOS应用开发实战:猫猫大作战-relationalStore 建库建表、增删改查 SQL、事务批量插入、与 Preference 键值取
2026/7/28 0:21:49
1.安装 System.Data.Sqlite1.0.1172.安装 sqlite.codefirst3.App.Config配置连接字符串5.配置<provider invariantName="System.Data.SQLite"type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>3.创建ApplicationDbContext和User表实体<connectionStrings><add name="SqliteDbContext"connectionString="data source=.\sqlite.db"providerName="System.Data.SQLite.EF6"/></connectionStrings><provider invariantName="System.Data.SQLite"type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>/// <summary>/// 实体类型/// </summary>public class EntityBase:ObservableObject{privateintid;/// <summary>/// 自增主键/// </summary>[Key][DatabaseGenerated(DatabaseGeneratedOption.Identity)]//自动递增publicintId{get=>id;set=>SetProperty(ref id,value);}private DateTime insertDate=DateTime.Now;/// <summary>/// 插入时间/// </summary>public DateTime InsertDate{get=>insertDate;set=>SetProperty(ref insertDate,value);}}[Table(nameof(User))]public class User:EntityBase{private string userName;public string UserName{get=>userName;set=>SetProperty(ref userName,value);}private string password;public string Password{get=>password;set=>SetProperty(ref password,value);}privateintrole;publicintRole{get=>role;set=>SetProperty(ref role,value);}}where T:class 约束为类public interface IRepository<T>where T:class{TGet(intid);intUpdate(T entity);intDelete(T entity);intInsert(T entity);List<T>GetAll();List<T>GetAll(string keyword);TSelect(string keyword);}public interface IUserRepository:IRepository<User>{}public class SqliteDbContext:DbContext{//读取配置文件connectionStrings,创建数据库映射publicSqliteDbContext():base("SqliteDbContext"){}public DbSet<User>Users{get;set;}protected overridevoidOnModelCreating(DbModelBuilder modelBuilder){//base.OnModelCreating(modelBuilder);//注入我们设置的SqliteDbContext,判断数据库是否存在?不存在则创建。var sqliteConnect=new SqliteCreateDatabaseIfNotExists<SqliteDbContext>(modelBuilder);//执行Database.SetInitializer(sqliteConnect);}}public abstract class RepositoryBase{protectedstaticSqliteDbContext db{get;}=new Lazy<SqliteDbContext>().Value;}public class UserRepository:RepositoryBase,IUserRepository{publicintDelete(User entity){db.Entry(entity).State=System.Data.Entity.EntityState.Deleted;returndb.SaveChanges();}public UserGet(intid){returndb.Users.Find(id);}public List<User>GetAll(){returndb.Users.ToList();}public List<User>GetAll(string keyword){returndb.Users.ToList().Where(t=>t.UserName.Contains(keyword)).ToList();}publicintInsert(User entity){db.Users.Add(entity);returndb.SaveChanges();}public UserSelect(string keyword){returndb.Users.ToList().Find(t=>t.UserName==keyword);}publicintUpdate(User entity){db.Entry(entity).State=System.Data.Entity.EntityState.Modified;returndb.SaveChanges();}}publicMainWindow(){InitializeComponent();}UserRepository xx=newUserRepository();privatevoidButton_Click(object sender,RoutedEventArgs e){User newUser=newUser();newUser.UserName="admin";newUser.Password="12345678";newUser.InsertDate=DateTime.Now;intcount=xx.Insert(newUser);if(count>0){System.Windows.MessageBox.Show("插入成功");}var entity=xx.GetAll().FirstOrDefault();}在WinForms开发中安装System.Data.SQLite、sqlite.codefirst和EntityFramework这三个库,各自承担不同的功能角色,以下是具体用途及分析:
核心作用:提供与SQLite数据库交互的底层ADO.NET接口。
功能细节:
SQLiteConnection、SQLiteCommand等类操作数据库。适用场景:
示例代码:
usingSystem.Data.SQLite;// 连接数据库using(varconnection=newSQLiteConnection("Data Source=mydb.sqlite")){connection.Open();// 执行SQL命令using(varcommand=newSQLiteCommand("SELECT * FROM Users",connection))using(varreader=command.ExecuteReader()){while(reader.Read()){Console.WriteLine(reader["Name"]);}}}核心作用:通过Code First模式自动生成SQLite数据库表结构。
功能细节:
适用场景:
示例代码(需先安装EntityFramework):
// 定义实体类publicclassUser{publicintId{get;set;}publicstringName{get;set;}}// 配置DbContextpublicclassMyDbContext:DbContext{publicDbSet<User>Users{get;set;}protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder){optionsBuilder.UseSqlite("Data Source=mydb.sqlite");}}// 自动生成数据库using(varcontext=newMyDbContext()){context.Database.EnsureCreated();// 若数据库不存在则创建}核心作用:提供高级ORM(对象关系映射)功能,简化数据访问层开发。
功能细节:
Microsoft.EntityFrameworkCore.Sqlite)支持多种数据库。适用场景:
示例代码(结合Microsoft.EntityFrameworkCore.Sqlite):
// 查询数据using(varcontext=newMyDbContext()){varusers=context.Users.Where(u=>u.Name.Contains("A")).ToList();foreach(varuserinusers){Console.WriteLine(user.Name);}}推荐组合:
System.Data.SQLite(直接操作数据库)。System.Data.SQLite+EntityFramework(ORM简化代码)。System.Data.SQLite+EntityFramework+sqlite.codefirst(Code First自动管理表结构)。注意事项:
Microsoft.EntityFrameworkCore.Sqlite(而非System.Data.SQLite)作为提供程序,以避免冲突。sqlite.codefirst非官方库,需评估其稳定性与维护性。EF6(Entity Framework 6) 是 Microsoft 提供的 对象关系映射(ORM)框架,用于简化 .NET 应用程序与数据库的交互。它通过将数据库表映射为 C#/VB.NET 对象,使开发者能以面向对象的方式操作数据,而无需直接编写 SQL 语句。