entity-framework - Entity Framework : removing entity when One-to-One PK association is specified

标签 entity-framework

我现有的数据库具有以下结构: enter image description here

我正在使用 EF Fluent API 来配置表之间的关系:

public GroupEntityConfiguration()
{
    HasMany(x => x.Employees).WithRequired().HasForeignKey(x => x.GroupId).WillCascadeOnDelete(true);
}

public EmployeeEntityConfiguration()
{            
    HasOptional(x => x.InnerGroupMember).WithRequired();
}

应用此配置后,我可以添加新的 Employee、新的 InnerGroupMember 或获取数据。当我尝试删除员工时出现问题。然后我得到一个异常:

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.

据我了解,上述异常与 GroupId 外键有关。尝试修复它,我将以下行添加到 EmployeeEntityConfiguration:

HasKey(x => new { x.Id, x.GroupId});

但是添加它后,我得到另一个异常,我认为该异常与 InnerGroupMember 对象有关:

Invalid column name 'Guest_Id'. Invalid column name 'Guest_GroupId'.

如果我注释掉 InnerGroupMember 导航属性并删除其配置,则可以删除 Employee。

您能否提示我做错了什么以及如何配置实体以便能够执行所有需要的操作?谢谢!

最佳答案

我有一个现有的 Group 实体,我想从员工组集合中删除员工:

var group = groupRepository.Find(groupId);
group.RemoveEmployee(employeeId);
_unitOfWork.Save();

Group 实体中的RemoveEmployee函数如下所示:

public void RemoveEmployee(int employeeId)
{
    var employee = Employees.Single(n => n.Id == employeeId);
    Employees.Remove(employee);
}

这就是我得到异常(exception)的原因:

The relationship could not be changed because one or more of the foreign-key properties is non-nullable....

阅读后this post我想修复它,在 EmployeeEntityConfiguration 中添加 HasKey(x => new { x.Id, x.GroupId}); 函数,这会导致第二个异常:

Invalid column name 'Guest_Id'. Invalid column name 'Guest_GroupId'.

实际上我在没有改变数据库结构的情况下完成了这一步(我的意思是添加HasKey函数)。为了使它工作,在Employees表中我必须创建复合键——Id和GroupId的组合,这也是一个外键。此修改会强制 InnerGroupMembers 表内发生更改。数据库结构现在如下所示: enter image description here

现在我可以按照我在开始时展示的方式删除 Employee。

无论如何,我不会采用这个解决方案。它们是实现我想要的东西的不同方法。以下是一些链接:

关于entity-framework - Entity Framework : removing entity when One-to-One PK association is specified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15313409/

相关文章:

xcode - 如何让Xcode核心数据代码生成的文件可以公开访问

c# - Entity Framework 代码优先 : How can I cast a set of entities returned from the database?

asp.net-mvc-3 - 使用 MSDeploy 进行 DevArt Entity Framework 部署

entity-framework - 来自数据库项目的脚手架 EF Core

c# - Entity Framework 无法删除数据库,正在使用的数据库

entity-framework - Entity Framework 5 - 添加迁移时可空枚举被忽略

c# - EF 核心 : how to validate data exists by condition in OnModelCreating

c# - 如何使用 Linq to Entity Framework 在表达式中使用函数?

c# - 插入时的自引用主键

wcf - 在基于 WCF 的企业应用程序中使用 Entity Framework 的哪个变体