如何删除实体框架中的多对多关系6 [英] How delete many-to-many relation in Entity Framework 6

查看:122
本文介绍了如何删除实体框架中的多对多关系6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,从数据库中删除项目,如果连接他们有很多关系

I have a problem with the removal of items from the database if connects them a many to many relationship

我的数据库看起来像

| [Project] | <-- | [JobInProject] | --> | [Job] |
=============     ==================     =========
| ProjectID |     | JobInProjectID |     | JobID |
|           |     | ProjectID      |     |       |
|           |     | JobID          |     |       |

项目作业表也被设置为其他表中的外键,但我认为没有问题,因为当我从作业表中删除项,其他表中的所有相关项目正确删除

Primary keys from Project and Job table are also set as foreign key in others tables but I think it isn't problem because when I remove item from Job table, it is removed correctly with all related items in others tables

所有外键都是通过约束设置的,而更新级联上的删除级联

All foreign keys are set by constraint and on delete cascade on update cascade

我用于删除作业项目的代码

Code which I use to delete job item

 Job job = await db.Jobs.FindAsync(id);
 db.Entry(job).State = EntityState.Deleted;
 await db.SaveChangesAsync();    

和项目:

Project project = await db.Projects.FindAsync(id);
db.Entry(project).State = EntityState.Deleted;
await db.SaveChangesAsync();

删除项目项目的代码仅从项目中删除数据表和 JobInProject 表不要删除作业和相关项目。

Code to remove project item remove only data from Project table and JobInProject table do not remove Job and related items.

当我修改代码以删除项目,如下所示:

When I modify code to remove Project like this:

 Project project = await db.Projects.FindAsync(id);

 foreach (var item in project.JobInProjects)
 {
     db.Entry(item.Job).State = EntityState.Deleted;
 }

 db.Entry(project).State = EntityState.Deleted;
 await db.SaveChangesAsync();

我在上等到db.SaveChangesAsync();


操作失败:无法更改关系,因为一个或多个外键属性为非-nullable。当对关系进行更改时,将相关的外键属性设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,否则必须删除不相关的对象。

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.

如何删除项目项目和相关的作业项目?

How can I remove Project item and related Job items ?

我将不胜感激的帮助

推荐答案

JobInProject 对象标记为已删除

foreach (var item in project.JobInProjects)
{
    db.Entry(item.Job).State = EntityState.Deleted;
    db.Entry(item).State = EntityState.Deleted; // <= line added
}

如果不这样做,EF将假设您不想删除该项目,并尝试将 JobInProject 中的两个外键设置为 null ,但当然一个或多个外键属性不可为空(两者都不是)。

If you don't do that, EF will assume you don't want to delete the item and try to set both foreign keys in JobInProject to null, but of course one or more of the foreign-key properties is non-nullable (both aren't).

这篇关于如何删除实体框架中的多对多关系6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆