我需要在Entity Framework中使用内部联接删除一些记录。
例如,我有User
,Role
和UserRoleMapping
表:
User => Id, Name
Role => Id, Name
UserRoleMapping => Id, UserId, RoleId
现在我需要删除属于Id = 2的角色的用户。
我需要触发查询,如下所示
Delete user
from User
inner join UserRoleMapping on User.Id = UserRoleMapping.UserId
where UserRoleMapping.RoleId = 2
这是否可以在实体框架中使用?
答案 0 :(得分:1)
在EF中,您需要首先加载实体,选择项目然后DeleteObject
。你需要这样做:
using (var context = new YourContext())
{
var item = (from user in context.User
join userRoleMapping in context.UserRoleMapping on user.Id equals userRoleMapping.UserId
where userRoleMapping.RoleId == 2
select user).ToList().ForEach(context.User.DeleteObject);
context.SaveChanges();
}
注意:
ObjectContext.DeleteObject(entity)
在上下文中将实体标记为已删除。 (之后删除了EntityState。)如果之后调用SaveChanges
,EF会向数据库发送SQL DELETE语句。如果违反了数据库中的引用约束,则将删除该实体,否则将引发异常
或
using (var context = new YourContext())
{
var items = (from user in context.User
join userRoleMapping in context.UserRoleMapping on user.Id equals userRoleMapping.UserId
where userRoleMapping.RoleId == 2
select user).ToList();
foreach (var item in items)
{
context.Entry(item).State = EntityState.Deleted;
}
context.SaveChanges();
}
或使用ExecuteStoreCommand
,您可以在这里找到more
using (var context = new YourContext())
{
context.ExecuteStoreCommand("DELETE FROM USER INNER JOIN USERROLEMAPPING ON USER.ID = USERROLEMAPPING.USERID WHERE USERROLEMAPPING .ROLEID = {0}", customId);
}