I have the following tables team and player where their are many players per team based on teamId being a guid. As you can see the first row in the team table with guid of empty i no its just a test has two records based on teamID in the players table
My Main question using entity framework how would i delete the team and the player in one go with entity framework
As you can see the frist record
So in my team grid I was just doing the following but as you see this is only grabbing the team object. Obv I could just hit out at the players object first and delete them first.
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);
}
This is my GetTeamByTeamId function
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);
}
}
This is asp.net by the way
Edits
I tried rankins suggesiton but have a an error on compile
Error 36 'soccerCmsDal.team' does not contain a definition for 'players' and no extension method 'players' accepting a first argument of type 'soccerCmsDal.team' could be found (are you missing a using directive or an assembly reference?) C:\new code\UniteCms\UniteCms\UniteCms\BackDoor\teams\default.aspx.cs 38 54 UniteCms
My attempt to add a foreign key

Ok now I have the foreign key setup its not working its giving me a null error
{
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();
}



cascading delete? (I thought this was enabled by default)_teamfrom @Rakin's answer contains the player you can also loop the collection and delete them one by one. Don't useforeachthough because that might throw an exception stating that the collection has changed. (there must be something like:_team.players)