.NET MAUI中SQLite CreateTableAsync无异常崩溃求助
.NET MAUI中SQLite调用崩溃无异常的解决方案
针对执行await db.CreateTableAsync<Profile>()时应用直接关闭且无异常的问题,从核心方向排查修复:
1. 修正异步方法调用的问题
ViewModel中的createProfiles使用async void,非事件场景下会导致未捕获异步异常直接终止应用,改为async Task并确保调用时正确等待:
// 修改ViewModel中的方法 private async Task CreateProfiles() { Profile tempProfile = new Profile { Name = "Test", Hostname = "0.0.0.0", Port = 23, }; try { await ProfileService.AddProfile(tempProfile); } catch (Exception ex) { Debug.WriteLine($"添加Profile失败: {ex.Message}"); } } // 页面加载时调用示例 protected override async void OnAppearing() { base.OnAppearing(); await CreateProfiles(); }
2. 替换为MAUI适配的数据库路径获取方式
Environment.SpecialFolder.LocalApplicationData在部分MAUI平台可能存在路径权限或识别问题,改用MAUI内置FileSystem类获取可靠路径:
// 修改ProfileService的Init方法 async Task Init() { if (db != null) return; var databasePath = Path.Combine(FileSystem.AppDataDirectory, "Profiles.db"); db = new SQLiteAsyncConnection(databasePath); try { await db.CreateTableAsync<Profile>(); } catch (Exception ex) { Debug.WriteLine($"创建表失败: {ex.Message}"); throw; } }
3. 确认NuGet包的正确性
确保安装适配MAUI的SQLite相关包:
- 安装
sqlite-net-pcl(选择最新稳定版) - 额外安装
SQLitePCLRaw.bundle_green,自动处理不同平台的原生SQLite依赖,避免因缺失原生库导致崩溃
4. 完善Profile实体定义
显式指定字符串字段非空约束,避免部分SQLite版本对空字符串的敏感处理:
public class Profile { [PrimaryKey, AutoIncrement] public int Id { get; set; } [NotNull] public string Name { get; set; } = string.Empty; [NotNull] public string Hostname { get; set; } = string.Empty; public int Port { get; set; } }
5. 确保数据库连接线程安全
若ProfileService为单例,加锁避免多线程重复初始化:
private static readonly object _lockObj = new object(); async Task Init() { if (db != null) return; lock (_lockObj) { if (db != null) return; var databasePath = Path.Combine(FileSystem.AppDataDirectory, "Profiles.db"); db = new SQLiteAsyncConnection(databasePath); } await db.CreateTableAsync<Profile>(); }
按以上步骤修改后,可捕获具体异常并解决崩溃问题,核心是修复async void带来的异常无法捕获问题,以及适配MAUI的路径和依赖包。
内容的提问来源于stack exchange,提问作者KnokTheBottle
相关产品推荐
相关产品推荐

