c# – 如何删除Entity Framework 6中的多对多关系

如果将数据库中的项目连接成多对多的关系,我就会遇到问题

我的数据库看起来像

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

Project和Job表中的主键也被设置为其他表中的外键但我认为这不是问题,因为当我从Job表中删除项时,它被正确删除,其他表中的所有相关项

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

我用来删除工作项的代码

 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();

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

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

 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();

我在await db.SaveChangesAsync()上遇到错误;线

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.

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

我将不胜感激

最佳答案 这是因为您没有将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,但当然一个或多个外键属性是不可为空的(两者都是都没有).

点赞