SqliteException: SQLite Error 19: ‘FOREIGN KEY constraint failed‘.

2024-02-14 12:04

本文主要是介绍SqliteException: SQLite Error 19: ‘FOREIGN KEY constraint failed‘.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需求:

发表动态可以没有标签,允许导航属性为空。

现象:

使用EFCore库框架,添加数据时出现。

截图:

数据表

    public class Moment{public ulong MomentID {  get; set; }public string Content { get; set; } = string.Empty;public ulong LableID {  get; set; }public Lable Lable { get; set; }    }
 public class Lable{public ulong LableID { get; set; }public string Name { get; set; } = string.Empty;public List<Moment> Moments { get; set; }}

DbContext

  public class DataBaseContext : DbContext{public DbSet<Moment> Moments { get; set; }public DbSet<Lable> Lables { get; set; }public string DbPath { get; }public DataBaseContext(){var folder = Environment.CurrentDirectory;DbPath = Path.Join(folder, "DataBase.db");Database.EnsureCreatedAsync();Log.Info("启动EFCore: " + DbPath);}protected override void OnModelCreating(ModelBuilder modelBuilder){             modelBuilder.Entity<Moment>().HasKey(x => x.MomentID);modelBuilder.Entity<Lable>().HasKey(x => x.LableID);modelBuilder.Entity<Moment>().HasOne(x => x.Lable).WithMany(x => x.Moments).HasForeignKey(x => x.LableID);}protected override void OnConfiguring(DbContextOptionsBuilder options){options.UseSqlite($"Data Source={DbPath}");options.LogTo(Log.Debug);}}

Program插入数据代码

namespace EFCore
{using System;using System.ComponentModel;using System.Linq;using System.Linq.Expressions;using System.Reflection;using System.Reflection.Metadata;using System.Text;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Migrations;using Microsoft.EntityFrameworkCore.Migrations.Operations;internal class Program{static void Main(string[] args){var folder = Environment.CurrentDirectory;var db = new DataBaseContext();Lable l = db.Lables.Where(x => x.Name == "意难平").ToList().FirstOrDefault(); ;if (l == null){l = new Lable();l.LableID = 1;l.Name = "意难平";db.Lables.Add(l);db.SaveChanges();Console.WriteLine("添加标签完毕");}else{Console.WriteLine("标签存在");}Moment query = db.Moments.Where(x => x.Content == "爱意随风起,风止意难平。").ToList().FirstOrDefault();if (query == null){query = new Moment();query.MomentID = (ulong)DateTime.Now.ToFileTime();query.Content = "爱意随风起,风止意难平。";db.Moments.Add(query);db.SaveChanges();Console.WriteLine("添加动态成功");}else{Console.WriteLine("动态存在");}Console.ReadKey();}}
}

以上代码运行则会报错,

SqliteException: SQLite Error 19: 'FOREIGN KEY constraint failed'.

表预览

改进代码V1

增加IsRequired(false)

则会报错

System.InvalidOperationException:“The property 'Moment.LableID' cannot be marked as nullable/optional because the type of the property is 'ulong' which is not a nullable type. Any property can be marked as non-nullable/required, but only properties of nullable types can be marked as nullable/optional.”

modelBuilder.Entity<Moment>().Property(x=>x.LableID).IsRequired(false);
modelBuilder.Entity<Moment>().Property(x => x.Lable).IsRequired(false);

 改进代码V2

删除上两行配置

modelBuilder.Entity<Moment>().HasOne(x => x.Lable).WithMany(x => x.Moments).HasForeignKey(x => x.LableID).IsRequired(false);

运行依然报错:FOREIGN KEY constraint failed

改进代码V3

保留V2,将Lable加个?,可空标记。

 public class Moment{public ulong MomentID {  get; set; }public string Content { get; set; } = string.Empty;public ulong? LableID {  get; set; }public Lable Lable { get; set; }    }

运行成功

查看数据库字段,已允许为Null了

结语

坑我好几天……不是专业后端……

搜博客翻墙,关键字HasForeignKey,IsRequired 都没找对方法。

谁知道就是缺个?

一键三连

如果可以帮助到你,记得一键三连。

点赞·评论·留言

大家的支持,即是我协作的动力,

或者可以请我喝杯咖啡哦

这篇关于SqliteException: SQLite Error 19: ‘FOREIGN KEY constraint failed‘.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/708454

相关文章

git ssh key相关

step1、进入.ssh文件夹   (windows下 下载git客户端)   cd ~/.ssh(windows mkdir ~/.ssh) step2、配置name和email git config --global user.name "你的名称"git config --global user.email "你的邮箱" step3、生成key ssh-keygen

DBeaver 连接 MySQL 报错 Public Key Retrieval is not allowed

DBeaver 连接 MySQL 报错 Public Key Retrieval is not allowed 文章目录 DBeaver 连接 MySQL 报错 Public Key Retrieval is not allowed问题解决办法 问题 使用 DBeaver 连接 MySQL 数据库的时候, 一直报错下面的错误 Public Key Retrieval is

sqlite不支持中文排序,采用java排序

方式一 不支持含有重复字段进行排序 /*** sqlite不支持中文排序,改用java排序* 根据指定的对象属性字段,排序对象集合,顺序* @param list* @param field* @return*/public static List sortListByField(List<?> list,String field){List temp = new ArrayList(

android java.io.IOException: open failed: ENOENT (No such file or directory)-api23+权限受权

问题描述 在安卓上,清单明明已经受权了读写文件权限,但偏偏就是创建不了目录和文件 调用mkdirs()总是返回false. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_E

UserWarning: mkl-service package failed to import

安装完成anaconda,并设置了两个环境变量  之后再控制台运行python环境,输入import numpy as np,提示错误 D:\InstallFolder\Anaconda3\lib\site-packages\numpy\__init__.py:143: UserWarning: mkl-service package failed to import, therefore

react笔记 8-19 事件对象、获取dom元素、双向绑定

1、事件对象event 通过事件的event对象获取它的dom元素 run=(event)=>{event.target.style="background:yellowgreen" //event的父级为他本身event.target.getAttribute("aid") //这样便获取到了它的自定义属性aid}render() {return (<div><h2>{

编译linux内核出现 arm-eabi-gcc: error: : No such file or directory

external/e2fsprogs/lib/ext2fs/tdb.c:673:29: warning: comparison between : In function 'max2165_set_params': -。。。。。。。。。。。。。。。。。。 。。。。。。。。。。。。。 。。。。。。。。 host asm: libdvm <= dalvik/vm/mterp/out/Inte

Python安装llama库出错“metadata-generation-failed”

Python安装llama库出错“metadata-generation-failed” 1. 安装llama库时出错2. 定位问题1. 去官网下载llama包 2.修改配置文件2.1 解压文件2.2 修改配置文件 3. 本地安装文件 1. 安装llama库时出错 2. 定位问题 根据查到的资料,发现时llama包中的execfile函数已经被下线了,需要我们手动修改代码后

收藏:解决 pip install 出现 error: subprocess-exited-with-error 错误的方法

在使用 pip 安装 Python 包时,有时候会遇到 error: subprocess-exited-with-error 错误。这种错误通常是由于 setuptools 版本问题引起的。本文将介绍如何解决这一问题 当你使用 pip install 安装某个 Python 包时,如果 setuptools 版本过高或过低,可能会导致安装过程出错,并出现类似以下错误信息:error: subpr

Nn criterions don’t compute the gradient w.r.t. targets error「pytorch」 (debug笔记)

Nn criterions don’t compute the gradient w.r.t. targets error「pytorch」 ##一、 缘由及解决方法 把这个pytorch-ddpg|github搬到jupyter notebook上运行时,出现错误Nn criterions don’t compute the gradient w.r.t. targets error。注:我用