You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sqlite-net-extensions时TextBlob为空及WithChildren方法失效求助

嘿,我来帮你搞定这个sqlite-net-extensions的问题!你遇到的TextBlob为空、WithChildren方法失效的情况,核心原因是没有用对sqlite-net-extensions提供的专属扩展方法——普通的SQLiteAsyncConnection操作根本不会处理TextBlob的序列化/反序列化,也不会触发关联数据的加载逻辑。咱们一步步修复:

1. 先确认依赖包是否装全

首先要确保你已经安装了正确的NuGet包:

  • sqlite-net-extensions(核心功能包)
  • sqlite-net-extensions.async(适配异步连接的扩展包)
  • Newtonsoft.Json(默认的TextBlob序列化器,必须安装)

2. 优化模型类(可选但更稳妥)

给模型类加上[Serializable]特性,确保序列化器能正常识别并处理它们:

[Serializable]
public class FoodNutrient 
{ 
    [PrimaryKey, AutoIncrement] 
    public int ID { get; set; } 
    public string foodname { get; set; } 
    public string sd { get; set; } 
    public string time { get; set; } 
    [TextBlob(nameof(nutrientsBlobbed))] 
    public List<NutrientItem> nutrients { get; set; } 
    public string nutrientsBlobbed { get; set; } 
} 

[Serializable]
public class NutrientItem 
{ 
    public string name { get; set; } 
    public string group { get; set; } 
    public string unit { get; set; } 
    public double value { get; set; } 
}

3. 替换数据库操作方法为扩展方法

普通的InsertAsync和Table().ToListAsync()完全不支持sqlite-net-extensions的特性,必须换成它提供的专属扩展方法:

// 别忘了引用这个命名空间,不然找不到扩展方法
using SQLiteNetExtensionsAsync.Extensions;

public class FoodDatabase 
{ 
    readonly SQLiteAsyncConnection database; 

    public FoodDatabase(string dbPath) 
    { 
        database = new SQLiteAsyncConnection(dbPath); 
        // 创建表(普通方法没问题,若后续有结构变更可换成InitTablesAsync)
        database.CreateTableAsync<FoodNutrient>().Wait();
        
        // 可选:手动指定序列化器(如果默认序列化出现异常时启用)
        // SQLiteNetExtensions.TextBlob.TextBlobOperations.SetTextSerializer(new NewtonsoftJsonSerializer());
    } 

    public Task<int> SaveFoodNutrientAsync(FoodNutrient foodNutrient) 
    { 
        // 用InsertOrReplaceWithChildrenAsync自动序列化TextBlob到nutrientsBlobbed字段
        return database.InsertOrReplaceWithChildrenAsync(foodNutrient, recursive: true);
    } 

    public Task<List<FoodNutrient>> GetFoodNutrientsAsync() 
    { 
        // 用GetAllWithChildrenAsync自动反序列化nutrientsBlobbed到nutrients列表
        return database.GetAllWithChildrenAsync<FoodNutrient>(recursive: true);
    } 
}

4. 注意旧数据的兼容问题

如果你之前用普通InsertAsync插入过数据,那些记录的nutrientsBlobbed字段是空的,所以查询出来的nutrients也会是空。需要重新插入这些数据,或者手动更新nutrientsBlobbed的值。

这样修改之后,TextBlob应该能正常完成序列化/反序列化,WithChildren相关的方法也能正常工作了!

内容的提问来源于stack exchange,提问作者DoubleD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:13:03