Asp.net如何使用实体框架删除一对多的对象

时间:2015-11-10 13:10:43

标签: c# asp.net entity-framework

我有以下表格的球队和球员,他们是每队的很多球员,基于teamId是一个guid。正如你可以看到团队表中的第一行guid为空我没有它只是一个测试有两个记录基于球员表中的teamID

enter image description here

我使用实体框架的主要问题如何使用实体框架一次性删除团队和玩家

enter image description here

正如你可以看到frist记录

所以在我的团队网格中我只是做了以下但是你看到这只是抓住团队对象。 Obv我可以先点击玩家对象并先删除它们。

        if (e.CommandName == "Delete")
        {

            GridDataItem item = e.Item as GridDataItem;
            Guid strId = new Guid(item.GetDataKeyValue("id").ToString());
             team  _team= _dal.GetTeamByTeamId (strId);


            _dal.SoccerEntities.teams.DeleteObject(team);


        }

这是我的GetTeamByTeamId函数

    public team GetTeamByTeamId(Guid  teamId)
         {
        try
        {
            if (teamId == Guid.Empty)
            {
                team _team = new team();

                return _team;
            }
            else
            {
                var q = SoccerEntities.teams.Where(p => p.id == teamId);

                if (q == null)
                    throw new EntityContextException(string.Format("A team could not be found {0}!", teamId));
                else
                    return q.ToList()[0];
            }
        }
        catch (Exception ex)
        {
            throw new EntityContextException("GetTeamByTeamId failed.", ex);
        }




    }

顺便说一句,这是asp.net

编辑

我尝试了Rankins建议,但编译错误

  

错误36'footballCmsDal.team'不包含'玩家'的定义,也没有扩展方法'玩家'可以找到'soccerCmsDal.team'类型的第一个参数(你是否错过了使用指令或程序集)引用?)C:\ new code \ UniteCms \ UniteCms \ UniteCms \ BackDoor \ teams \ default.aspx.cs 38 54 UniteCms

我尝试添加外键 enter image description here

好的,现在我的外键设置不起作用,它给我一个空错误

 {
            GridDataItem item = e.Item as GridDataItem;
            Guid strId = new Guid(item.GetDataKeyValue("id").ToString());
            team _team = _dal.SoccerEntities.teams.FirstOrDefault(p => p.id == strId);
            if (_team != null)
            {
                foreach (player _player in _team.players)
                {
                    _dal.SoccerEntities.players.DeleteObject(_player);
                }
                _dal.SoccerEntities.teams.DeleteObject(_team);
            }
            _dal.SoccerEntities.SaveChanges();


        }

enter image description here

1 个答案:

答案 0 :(得分:1)

  GridDataItem item = e.Item as GridDataItem;
            Guid strId = new Guid(item.GetDataKeyValue("id").ToString());
            team _team = _dal.SoccerEntities.teams.FirstOrDefault(p => p.id == strId);
            if (_team != null)
            {

                 if( _team.players!= null &&  _team.players.Count>0)
                 { var _palayers = _team.players.ToList();
                    foreach (player _player in _palayers )
                    {
                        _dal.SoccerEntities.players.DeleteObject(_player);
                    }
                 }
                _dal.SoccerEntities.teams.DeleteObject(_team);
            }
            _dal.SoccerEntities.SaveChanges();