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

如何自动分配外键?SQLite Browser与Dapper的实操方案

解决SQLite + Dapper中外键自动关联的问题

你的问题核心是插入Person后没拿到自动生成的PersonID,导致没法把它赋值给Course的PersonID字段。下面是具体解决步骤:

1. 修改SavePerson方法,获取插入后的自增PersonID

SQLite的自增主键(通常设为INTEGER PRIMARY KEY AUTOINCREMENT)插入后,可以通过last_insert_rowid()函数获取刚生成的ID。用Dapper的ExecuteScalar执行插入并返回该ID,再赋值给传入的Person对象:

public static void SavePerson(PersonModel person)
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        // 插入后返回生成的PersonID
        int newPersonId = cnn.ExecuteScalar<int>(
            "insert into Person (Name) values (@Name); select last_insert_rowid();", 
            person);
        // 将新ID赋值给Person对象的属性
        person.PersonID = newPersonId;
    }
}

2. 修改AddCourse方法,关联PersonID到Course

现在Person对象已经持有有效的PersonID,直接将其赋值给Course的PersonID字段,插入时一并写入数据库:

public static void AddCourse(PersonModel person, CourseModel course)
{
    // 给Course的外键字段赋值
    course.PersonID = person.PersonID;
    
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        // 插入时包含PersonID字段,完成外键关联
        cnn.Execute(
            "insert into Course (CourseName, PersonID) values (@CourseName, @PersonID)", 
            course);
    }
}

3. 确认数据库外键约束配置

在SQLite Browser中确保Course表的PersonID字段已正确设置外键:

  • 打开Course表的设计界面
  • 找到PersonID字段,设置外键关联到Person(PersonID)
  • 注意:SQLite默认关闭外键约束,需在连接字符串中添加Foreign Keys=True,示例:Data Source=your_database.db;Foreign Keys=True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:27:30