EF Entitystate从多对多中删除1条记录

时间:2015-12-28 14:48:48

标签: c# asp.net-mvc database entity-framework

所以我尝试从多个表中删除1个记录。但是,它不会删除任何内容吗?

我尝试删除UserId ==登录用户的Id的记录,以及GroupId == id是从多个表到GroupUser的链接给出的id(带有字段:UserId)和GroupId):

    public IActionResult UnSubscribe(Int16 id)
    {
        if(User.GetUserId() != null)
        {
            GroupUser groupToDel = _MyContext.GroupUser.Where(g => g.GroupId == id).FirstOrDefault();
            groupToDel.UserId+=User.GetUserId();

            _MyContext.Entry(groupToDel).State = EntityState.Deleted;
            _MyContext.SaveChanges(); 
            return RedirectToAction("Index", "Group");
        }
        else
        {
            throw new Exception("There was an Error!");
        }
    }

1 个答案:

答案 0 :(得分:0)

你认为这比我想象的要困难,你应该尝试这样做:

GroupUser groupToDel = _MyContext.GroupUser.Where(g => g.GroupId == groupid 
                                                  && g.UserId == userid).First();

_MyContext.GroupUser.Remove(groupToDel);
_MyContext.SaveChanges();