如何在Xamarin应用中用C#向SQLite数据库插入数据?
解决Xamarin中SQLite数据插入问题
你使用的是SQLite-net异步库,它的API设计和EF框架不同,不会自动生成实体集合属性(比如db.Doctors),也没有SaveChangesAsync方法。要实现和读取逻辑风格一致的数据插入,直接使用InsertAsync方法即可,和读取时调用Table<Doctors>()的思路匹配。
正确的插入代码示例
var newDoc = new Doctors { Name = "John Doe" }; string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "healthcare.db"); SQLiteAsyncConnection db = new SQLiteAsyncConnection(dbPath); // 直接调用InsertAsync插入单条数据 await db.InsertAsync(newDoc);
补充说明
- 若需要批量插入多条数据,可使用
InsertAllAsync方法:var docsList = new List<Doctors> { new Doctors { Name = "John Doe" }, new Doctors { Name = "Jane Smith" } }; await db.InsertAllAsync(docsList); - 如果你已有全局复用的
db实例,无需每次插入都重新创建SQLiteAsyncConnection,直接复用即可。
内容的提问来源于stack exchange,提问作者vytaute
相关产品推荐
相关产品推荐

