我需要使用实体框架中的内部联接删除一些记录。
例如,我有User,Role和UserRoleMapping表:
User => Id, Name
Role => Id, Name
UserRoleMapping => Id, UserId, RoleId
Run Code Online (Sandbox Code Playgroud)
现在我需要删除属于 Id = 2 角色的用户。
我需要触发查询,如下所示
Delete user
from User
inner join UserRoleMapping on User.Id = UserRoleMapping.UserId
where UserRoleMapping.RoleId = 2
Run Code Online (Sandbox Code Playgroud)
这在实体框架中可能吗?
在 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();
}
Run Code Online (Sandbox Code Playgroud)
笔记:
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();
}
Run Code Online (Sandbox Code Playgroud)
或使用ExecuteStoreCommand,在这里您可以找到更多
using (var context = new YourContext())
{
context.ExecuteStoreCommand("DELETE FROM USER INNER JOIN USERROLEMAPPING ON USER.ID = USERROLEMAPPING.USERID WHERE USERROLEMAPPING .ROLEID = {0}", customId);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4997 次 |
| 最近记录: |