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

C# Code First SQLite如何实现好友记录关联多张照片存储

报错原因

你当前使用的SQLite Code First库(通常为sqlite-net-pcl)不支持直接将List<int>这类集合类型映射为SQLite的原生存储字段,同时你也没有正确定义「好友-照片」的一对多关联关系,因此运行会报错。

正确实现方案

推荐搭配SQLiteNetExtensions库实现关系映射,先通过NuGet安装两个依赖包:

  • sqlite-net-pcl
  • SQLiteNetExtensions

1. 调整实体类定义

using SQLite;
using SQLiteNetExtensions.Attributes;
using System.Collections.Generic;

public class Friend
{
    [PrimaryKey, AutoIncrement]
    public int FriendId { get; set; }

    [NotNull]
    [MaxLength(50)]
    public string FullName { get; set; }

    [NotNull]
    [MaxLength(50)]
    public string Phone { get; set; }

    // 一对多导航属性,关联当前好友的所有照片
    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<FriendImage> Images { get; set; } = new List<FriendImage>();
}

public class FriendImage
{
    [PrimaryKey, AutoIncrement]
    public int ImageId { get; set; }
    public string ImageName { get; set; }

    // 外键,关联所属好友的ID
    [ForeignKey(typeof(Friend))]
    public int FriendId { get; set; }

    // 可选的多对一导航属性,方便反向查询照片所属好友
    [ManyToOne]
    public Friend BelongToFriend { get; set; }
}

2. 数据操作示例

插入带多张照片的好友数据

使用扩展方法InsertWithChildren自动处理关联关系,不需要手动维护外键:

// 构造好友对象,同时绑定多张照片
var newFriend = new Friend
{
    FullName = "张三",
    Phone = "13800138000",
    Images = new List<FriendImage>
    {
        new FriendImage { ImageName = "zhangsan_202401.jpg" },
        new FriendImage { ImageName = "zhangsan_202402.jpg" }
    }
};

// 插入数据,自动关联好友和照片的外键
db.InsertWithChildren(newFriend, recursive: true);

查询好友及关联的所有照片

使用扩展方法GetWithChildren直接拿到带照片列表的好友对象:

// 查询Id为1的好友,同时加载所有关联照片
var friend = db.GetWithChildren<Friend>(1, recursive: true);
var friendAllImages = friend.Images;

不依赖第三方扩展的原生实现方案

如果你不想引入SQLiteNetExtensions,可以手动处理关联逻辑:

  • Friend类不需要关联属性,FriendImage类保留FriendId外键字段
  • 插入时先插入Friend对象,拿到生成的FriendId,再给所有FriendImage赋值该Id后逐个插入
  • 查询时先查Friend对象,再用FriendId作为条件查询FriendImage表得到所有对应照片,手动赋值给自定义的Friend.Images属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:06:03