简体   繁体   中英

EF Entitystate delete 1 record from Many To Many

So I try to delete 1 record from a many to many table. However, it doesn't delete anything?

I try to delete the record where the UserId == the Id of the logged in user and where the GroupId == the id is the id given with the link from the many to many table called GroupUser (with the fields: UserId and 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!");
        }
    }

You're making this more difficult than it is I think, you should try just doing this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM