在级联删除实体框架

在级联删除实体框架

本文介绍了在级联删除实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有实体框架4.1删除相关行的问题。我有一个关系表

I have problem with deleting related rows in Entity Framework 4.1. I have tables with relations

图书1< ---> * BookFormats

Book 1<--->* BookFormats

我已经设置了上删除级联:

I have set the on delete cascade:

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



EDMX财产

The EDMX property

然后,我想删除我的相关簿中的所有 BokFormats 项目对象:

Then, I want to remove the all BokFormats items related to my Book object:

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



不过,我得到的错误:

But, I get the error:

操作失败:关系不能被改变,因为
的一个或多个外键的属性是不可为空。当
变化有关系提出的有关外键属性为
设置为空值。如果外键不支持空值,$ B $巴新的关系必须定义,外键属性必须是
指派另一非空值,或者无关的对象必须是
删除

我跑出了如何删除这些对象的想法。 ?任何想法

I ran out of ideas on how to delete these objects. Any ideas?

推荐答案

级联删除概念如下:当你从数据库的所有realted BookFormats将为您删除删除图书SQL服务器(请注意它并没有多么书的缺失将通过EF或原始SQL启动)。因此,它无关的任务:我想删除有关我的书都BokFormats。要acomplish它,你需要somethind是这样的:

Cascade deletions concept is as follows: when you delete Book from db all realted BookFormats will be deleted for you by SQL Server (please note it doesn't matter how deletion of Book will be initiated via EF or raw SQL). Thus it has nothing to do with task: "I want to delete all BokFormats related to my Book". To acomplish it you need somethind like this:

foreach(var m in m.db.BookFormats.Where(f=>f.BookID = bookID))
                {
                    m.db.BookFormats.Remove(m);
                }
                m.db.SaveChanges();

这篇关于在级联删除实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:31