gpt4 book ai didi

c# - 删除级联的 Entity Framework

转载 作者:可可西里 更新时间:2023-11-01 08:02:11 24 4
gpt4 key购买 nike

我在删除 Entity Framework 4.1 中的相关行时遇到问题。我有关系表

书籍 1<--->* 书籍格式

我已经设置了删除级联:

ALTER TABLE [dbo].[BookFormats]  WITH CHECK ADD  CONSTRAINT [FK_BookFormats_Book] 
FOREIGN KEY([BookID]) REFERENCES [dbo].[Book] ([BookID]) on delete cascade

EDMX 属性

enter image description here

然后,我想删除与我的 Book 对象相关的所有 BokFormats 项:

 var originalBook = m.db.Book.First(x => x.BookID == bookId);
originalBook.BookFormats.Clear();
m.db.SaveChanges();

但是,我得到了错误:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

我想不出如何删除这些对象。有什么想法吗?

最佳答案

您可以使用 RemoveRange :

m.db.BookFormats.RemoveRange(originalBook.BookFormats);
m.db.SaveChanges();

但这是针对 EF 6.0

关于c# - 删除级联的 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005948/

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