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

.NET MAUI中sqlite-net-pcl关联数据未自动插入的问题

问题解答

sqlite-net-pcl的基础API不会自动处理关联数据的级联插入,必须配合sqlite-net-extensions的扩展方法和正确的实体配置才能实现自动插入,不需要手动逐条插入关联数据。

核心原因

普通的InsertAsync方法仅处理当前实体,不会遍历并插入关联的子实体(包括中间表UserCountry的记录)。要实现关联数据自动插入,必须依赖sqlite-net-extensions提供的专用方法,并正确标记实体间的关联关系。

修正步骤

1. 完善实体关联标记

你的实体缺少sqlite-net-extensions的关联属性,需根据关联类型补充标记:

若为User与Country的多对多关联(通过UserCountry中间表)

public class User
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    
    // 标记多对多关联,指定中间表及关联字段
    [ManyToMany(typeof(UserCountry), nameof(UserCountry.UserId), nameof(UserCountry.CountryId))]
    public List<Country> Countries { get; set; } = new List<Country>();
}

public class Country
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    
    // 可选:反向关联,方便双向查询
    [ManyToMany(typeof(UserCountry), nameof(UserCountry.CountryId), nameof(UserCountry.UserId))]
    public List<User> Users { get; set; } = new List<User>();
}

public class UserCountry
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [ForeignKey(typeof(User))]
    public int UserId { get; set; }
    [ForeignKey(typeof(Country))]
    public int CountryId { get; set; }
}

若为User到UserCountry的一对多关联

public class User
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    
    // 标记一对多关联,指定级联操作(包含插入)
    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<UserCountry> Countries { get; set; } = new List<UserCountry>();
}

注意:关联属性必须是带get/set的Property,不能是Field(原代码中public List<UserCountry> Countries;是字段,需改为属性)。

2. 使用扩展方法执行插入

替换普通的InsertAsync,改用sqlite-net-extensions的InsertWithChildrenAsync方法,开启递归插入:

// 插入单个用户及关联数据
await _asyncDbConnection.InsertWithChildrenAsync(user, true);

// 插入用户列表(建议用事务保证原子性)
using var transaction = await _asyncDbConnection.BeginTransactionAsync();
try
{
    foreach (var user in userList)
    {
        await _asyncDbConnection.InsertWithChildrenAsync(user, true);
    }
    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

第二个参数true表示递归插入所有关联的子实体,包括中间表UserCountry的记录。

额外说明

你已配置的PRAGMA foreign_keys = ON;是正确的,确保了外键约束生效,无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:30:16