Entity framework 如何在实体框架中使用内部联接删除或更新?

Entity framework 如何在实体框架中使用内部联接删除或更新?,entity-framework,Entity Framework,我需要在实体框架中使用内部连接删除一些记录 例如,我有用户、角色和用户角色映射表: 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

我需要在实体框架中使用内部连接删除一些记录

例如,我有
用户
角色
用户角色映射
表:

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

这在实体框架中是可能的吗

在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(实体)
在上下文中将实体标记为已删除。(它的EntityState在此之后被删除。)如果之后调用
SaveChanges
,EF将向数据库发送SQL DELETE语句。如果数据库中没有违反引用约束,则将删除实体,否则将引发异常

或者使用
ExecuteStoreCommand
,您可以在这里找到


将有一个用户列表,但以下查询将只删除一条记录。@GopinathNavaneethan Check update it从select中删除所有项。上述代码将起作用,但从性能角度看,它将失败。这就是为什么我需要带delete:-(@gopinathnavenethan)的内部连接查询,您也可以尝试
ExecuteStoreCommand()
应该更优化。对此我很抱歉,但我也需要更通用的查询。对于这种操作,值得检查。
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();
}
using (var context = new YourContext())
{
    context.ExecuteStoreCommand("DELETE FROM USER INNER JOIN USERROLEMAPPING ON USER.ID = USERROLEMAPPING.USERID WHERE USERROLEMAPPING .ROLEID = {0}", customId);
}