使用 RIA 服务和实体框架通过导航属性从数据库表中删除实体
我有 3 个标准化表,其中包括员工、部门和员工到部门。我希望能够将一名员工分配给一个或多个部门,因此需要链接表(EmployeesToDepartments)。我可以使用元数据中的 [Include] 属性成功查询数据库并通过导航属性提取实体的完整层次结构
this.ObjectContext.Employees.Include("EmployeesToDepartments").Include("EmployeesToDepartments.Department")
,从而允许我访问给定员工的部门。在尝试删除 [EmployeesToDepartments] 表中 [Employee] 和 [Department] 之间的链接时,出现外键约束错误。
我简化了我的模型,只包含 [Employees] 和 [EmployeesToDepartments] 之间的一个导航属性。 [Employees].[ID] 和 [EmployeesToDepartments].[IDEmployee] 之间的外键约束阻止我更新EmployeesToDepartments 表。通过关系设置删除此内容后,我现在可以更新表。我现在可以执行以下代码,
foreach (var rel in _employee.EmployeesToDepartments)
{
_employee.EmployeesToDepartments.Remove(rel);
}
_domainContext.SubmitChanges();
不会出现错误。
我期望看到 RelEmployeesToDepartments 中 IDEmployee 已被删除的条目。我在表中看到的是 IDEmployee 之前的值 0。
是否可以强制发出 DELETE 语句?我是否误解了这里的基本概念?
任何帮助将不胜感激。
I have 3 normalised tables consisting of Employees, Departments and EmployeesToDepartments. I wish to be able to assign an Employee to one or more Department, hence the link table (EmployeesToDepartments). I can successfully query the database and extract the full hierarchy of entities via the Navigation properties using
this.ObjectContext.Employees.Include("EmployeesToDepartments").Include("EmployeesToDepartments.Department")
plus the [Include] attribute in the metadata, thus allowing me to access the Departments for a given Employee. Upon trying to remove a link between an [Employee] and [Department] in the [EmployeesToDepartments] table I was given a Foreign Key Constrain error.
I have simplified my model to include just one navigation property between [Employees] and [EmployeesToDepartments]. A Foreign Key constraint between[Employees].[ID] and [EmployeesToDepartments].[IDEmployee] was preventing me from updating the EmployeesToDepartments table. With this removed via a Relationship setting I can now update the table. I can now execute the following code
foreach (var rel in _employee.EmployeesToDepartments)
{
_employee.EmployeesToDepartments.Remove(rel);
}
_domainContext.SubmitChanges();
without error.
I was expecting to see the entries in the RelEmployeesToDepartments with the IDEmployee to have been deleted. What I see in the table are the value 0 where the IDEmployee previously was.
Is it possible to force a DELETE statement to be issued? Am I misunderstanding the basic concepts here?
Any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
删除导航属性中的实体只会破坏实体之间的链接。您必须从 EntitySet 中删除才能实现您想要的。
前任)
myDomainContext.EmployeeDepartments.Remove(employeeDepartmentToRemove);
myDomainContext.SubmitChanges();
Removing entities in navigation property only breaks the link between entities. You have to delete from the EntitySet to achive what you want.
ex)
myDomainContext.EmployeeDepartments.Remove(employeeDepartmentToRemove);
myDomainContext.SubmitChanges();