我有三张桌子: -
SecurityRole&团体和SecurityRoleGroups。 (securityrole可以有很多组。一个组可以有很多安全组件)
其中SecurityRoleGroup表是多对多关系表,而Entity框架不会映射此表。所以我想删除属于某个SecurityRole的所有SecurityRoleGroup记录。如果我写点什么
SecurityRole securityrole = FindAllRole(id);
tms.SecurityRoles.Remove(securityrole).Groups.Where(a=> a.GroupID == group.GroupID)
它只会从SecurityRoleGroup中删除所需的记录,还会删除相关的SecurityRole记录吗?
::: UPDATE :::
但是如果我想删除多对多记录只是因为它在currentGroups [c]数组中。我可以写下如下内容: -
if (group.GroupID == currentGroups[c])
{
var securityrole = tms.SecurityRoles.Where(a => a.SecurityRoleID == id).Include(p => p.Groups).SingleOrDefault();
(securityrole != null) {
securityrole.Groups.Remove(group);
}
}
答案 0 :(得分:2)
如果只想删除存储在链接表中的关系,而不是实体SecurityRole
和Group
,则必须将实体附加到当前关系中的上下文(即{{ 1}}必须位于Group
实体的Groups
集合中,然后您必须从此集合中删除它们。 EF将跟踪此更改并将DELETE语句单独写入链接表。
可以这样实现:
SecurityRole
修改强>
如果您只想删除符合条件的链接记录,请使用using (var context = new MyContext())
{
var securityRole = context.SecurityRoles
.Include(s => s.Groups) // or Include("Groups") for EF <= 4.0
.SingleOrDefault(s => s.SecurityRoleId == givenId);
if (securityRole != null)
{
securityRole.Groups.Clear();
context.SaveChanges();
}
}
代替Remove
:
Clear
(假设 if (securityRole != null)
{
foreach (var group in securityRole.Groups
.Where(g => currentGroups[c].Contains(g.GroupID)).ToList())
{
securityRole.Groups.Remove(group);
}
context.SaveChanges();
}
是组ID的集合)