[英]C# FrameworkCore and MySQL: Cannot delete or update a parent row: a foreign key constraint fails
Need some help here... I am copying code directly from one of my school classes, and they show the result in their code, but each time I run it, I get the following exception error: 这里需要一些帮助...我直接从我的一个学校课程中复制代码,它们在代码中显示结果,但是每次运行它时,都会出现以下异常错误:
Exception has occurred: CLR/Microsoft.EntityFrameworkCore.DbUpdateException An unhandled exception of type 'Microsoft.EntityFrameworkCore.DbUpdateException' occurred in Microsoft.EntityFrameworkCore.dll: 'An error occurred while updating the entries.
发生了异常:CLR / Microsoft.EntityFrameworkCore.DbUpdateException Microsoft.EntityFrameworkCore.dll中发生了类型为'Microsoft.EntityFrameworkCore.DbUpdateException'的未处理异常:'更新条目时发生了错误。 See the inner exception for details.'
有关详细信息,请参见内部异常。 Inner exceptions found, see $exception in variables window for more details.
找到内部异常,有关更多详细信息,请参见变量窗口中的$ exception。 Innermost exception MySql.Data.MySqlClient.MySqlException : Cannot delete or update a parent row: a foreign key constraint fails (
movies
.film_actor
, CONSTRAINTfilm_actor_actor
FOREIGN KEY (ActorId
) REFERENCESactor
(actorid
)) at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at MySqlConnector.Core.ResultSet.d__1.MoveNext() in C:\\projects\\mysqlconnector\\src\\MySqlConnector\\Core\\ResultSet.cs:line 44最里面的异常MySql.Data.MySqlClient.MySqlException:不能删除或更新父行,外键约束失败(
movies
。film_actor
,约束film_actor_actor
外键(ActorId
)参考actor
(actorid
))在System.Runtime.ExceptionServices.ExceptionDispatchInfo。在C:\\ projects \\ mysqlconnector \\ src \\ MySqlConnector \\ Core \\ ResultSet.cs:line 44中的MySqlConnector.Core.ResultSet.d__1.MoveNext()处抛出()
Here is the method being called: 这是被调用的方法:
internal static void DeleteItem()
{
Console.WriteLine("Delete an Actor");
Console.WriteLine("Enter an Actor ID");
var actorId = Console.ReadLine().ToInt();
var actor = MoviesContext.Instance.Actors.SingleOrDefault(a => a.ActorId == actorId);
if (actor == null) {
Console.WriteLine($"Actor with id {actorId} not found.");
}
else {
Console.WriteLine("Existing Actors");
WriteActors();
MoviesContext.Instance.Actors.Remove(actor);
MoviesContext.Instance.SaveChanges();
Console.WriteLine("With actor removed.");
WriteActors();
}
}
I have checked my code over and over again and it matches the instructor's code perfectly. 我已经一遍又一遍地检查我的代码,它完全匹配了老师的代码。 Unfortunately, no one is addressing my question through the college Blackboard, so I brought my question here.
不幸的是,没有人通过大学黑板来解决我的问题,所以我在这里提出了我的问题。
The framework reverse-engineered the database to build all of the scaffolding for the code. 该框架对数据库进行了逆向工程,以构建代码的所有支架。 The program is throwing this exception when the MySQL statement for
SaveChanges()
is sent. 发送针对
SaveChanges()
的MySQL语句时,程序将引发此异常。
However, it must be from this table, because SaveChanges()
is used in an earlier part of the code for something else, and it doesn't throw any errors. 但是,它必须来自此表,因为
SaveChanges()
在代码的较早部分中用于其他用途,并且不会引发任何错误。
Ideas? 有想法吗? This is driving me Looney!
这让我发疯! Thanks.
谢谢。 :)
:)
Using: C# ConsoleTables EntityFrameworkCore + .Design + .Tools // Used as a DotNetCliToolReference + .Tools.DotNet // Used as a DotNetCliToolReference + .MySql + .MySql.Design
I don't know anything about constraints, but here is the section of code I found that the framework generated that may be a contributor: 我对约束一无所知,但是在这部分代码中,我发现生成的框架可能是促成因素的:
modelBuilder.Entity<FilmActor>(entity =>
{
entity.HasKey(e => new { e.FilmId, e.ActorId });
entity.ToTable("film_actor");
entity.HasIndex(e => e.ActorId)
.HasName("film_actor_actor_idx");
entity.Property(e => e.FilmId).HasColumnType("int(11)");
entity.Property(e => e.ActorId).HasColumnType("int(11)");
entity.HasOne(d => d.Actor)
.WithMany(p => p.FilmActor)
.HasForeignKey(d => d.ActorId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("film_actor_actor");
entity.HasOne(d => d.Film)
.WithMany(p => p.FilmActor)
.HasForeignKey(d => d.FilmId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("film_actor_film");
});
Perhaps I'm not using this model correctly somewhere? 也许我在某处没有正确使用此模型?
RESOLUTION 解析度
After much help below I was able to accomplish the fix by simply creating a loop that went through the associated table film_actor and deleted any rows with the ActorId that was related to the actor being deleted. 在下面提供了很多帮助之后,我能够通过简单地创建一个循环来完成修复,该循环遍历了关联的表film_actor并删除了与要删除的actor相关的具有ActorId的任何行。 Here is the quick loop I put in before the
SaveChanges()
method gets executed: 这是我在执行
SaveChanges()
方法之前放入的快速循环:
foreach (var tatertot in MoviesContext.Instance.FilmActors) {
if(tatertot.ActorId == actorId) {
MoviesContext.Instance.FilmActors.Remove(tatertot);
}
}
I'd like to thank everyone for their help. 我要感谢大家的帮助。 I'm sure I'll have more as this class goes on!
随着课程的进行,我相信我还会有更多! Thank you.
谢谢。 :)
:)
This is the vital piece of information: 这是至关重要的信息:
Cannot delete or update a parent row: a foreign key constraint fails (movies.film_actor, CONSTRAINT film_actor_actor FOREIGN KEY (ActorId) REFERENCES actor (actorid).
无法删除或更新父行:外键约束失败(movies.film_actor,CONSTRAINT film_actor_actor FOREIGN KEY(ActorId)参考actor(actorid)。
If I'm reading the details correctly, what that means is that there is a value in the column film_actor_actor
in movies.film_actor
that points to the id (in the column ActorId
) of the actor you are trying to delete. 如果我正确地阅读了详细信息,那意味着在
film_actor_actor
的movies.film_actor
列中有一个值指向您要删除的演员的ID(在ActorId
列中)。
The foreign key constraint means you can't delete the actor before removing the film_actor
pointing to it first, because if you did, the film_actor
would be pointing to a non-existing row, which would render your database inconsistent. 外键约束意味着您不能在删除
film_actor
指向它的film_actor
之前删除该film_actor
,因为如果这样做,则film_actor
将指向一个不存在的行,这将导致数据库不一致。
Solution: You need to delete any and all references to an actor row before you can delete the actor row itself. 解决方案:您需要删除对参与者行的所有引用,然后才能删除参与者行本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.