gpt4 book ai didi

c# - SQLite EF 核心 - 'FOREIGN KEY constraint failed'

转载 作者:行者123 更新时间:2023-12-04 04:05:14 26 4
gpt4 key购买 nike

在我的 ASP.Net Core 项目中,我在启动时遇到了这个异常,因为我正在运行时初始化数据库:

fail: Microsoft.EntityFrameworkCore.Update[10000]

An exception occurred in the database while saving changes for context type 'BlazorWeb.Server.Data.SQLiteTestDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.

Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'FOREIGN KEY constraint failed'.

at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
....


我的模型:
public class ObjectModel : BaseEntity
{
[Key]
public int Id { get; set; }
public String Name { get; set; }
public String PreviewImage { get; set; }
public String TagName { get; set; }

// Foreign keys---
public int TypeId { get; set; }
public ObjectTypeModel TypeModel { get; set; }
//---
}

public class ObjectTypeModel : BaseEntity
{
[Key]
public int TypeId { get; set; }
public String Name { get; set; }
public String PreviewImage { get; set; }
public String TagName { get; set; }

public ICollection<ObjectModel> Objects { get; set; }
}
我的 SQLite OnModelCreating DbContext 中的方法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ObjectModel>()
.HasOne<ObjectTypeModel>(d => d.TypeModel)
.WithMany(dm => dm.Objects)
.HasForeignKey(dkey => dkey.TypeId);
}
从自动生成的迁移类:
            name: "Objects",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
CreatedOn = table.Column<DateTime>(nullable: false),
ModifiedOn = table.Column<DateTime>(nullable: false),
Name = table.Column<string>(nullable: true),
PreviewImage = table.Column<string>(nullable: true),
TagName = table.Column<string>(nullable: true),
TypeId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Objects", x => x.Id);
table.ForeignKey(
name: "FK_Objects_ObjectTypes_TypeId",
column: x => x.TypeId,
principalTable: "ObjectTypes",
principalColumn: "TypeId",
onDelete: ReferentialAction.Cascade);
});
在我的 initialize 方法中,我只用一些数据填充它并将它们保存到上下文中。但是数据库永远不会收到这些记录,也会发生外键约束异常。
任何人都可以帮助我 - 我做错了什么吗?
编辑
我发现在 SaveChangeAsync() 方法运行时发生异常。
我的覆盖 SaveChangesAsyn()方法:
     public Task<int> SaveChangesAsync()
{
var entries = ChangeTracker
.Entries()
.Where(e => e.Entity is BaseEntity && (
e.State == EntityState.Added ||
e.State == EntityState.Modified));

foreach (var entityEntry in entries)
{
// overwrite `ModifiedOn` value with current date.
((BaseEntity)entityEntry.Entity).ModifiedO=
DateTime.Now;

// set `CreatedOn` to current date if its not already set.
if (entityEntry.State == EntityState.Added)
{
((BaseEntity)entityEntry.Entity).CreatedOn = DateTime.Now;
}
}
return base.SaveChangesAsync();
}

最佳答案

我在尝试删除与另一个对象具有一对多关系的记录时遇到了同样的错误。
问题是在 DataContext 中没有定义级联删除,您可以将以下内容添加到您的 DataContext 中:

            
modelbuilder.Entity<ObjectTypeModel>()
.HasMany(dm => dm.Objects)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);

关于c# - SQLite EF 核心 - 'FOREIGN KEY constraint failed',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62626031/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com