0
Answer

Please advise - "An error occurred while saving entities"

nave

nave

11y
4.9k
1
Im trying to to insert rows into 2 tables based on a 2 arrays like this:

TeamLevelType[] teamTypeArray = teamType.ToArray();

  foreach (TeamLevelType i in teamTypeArray)
  {
  int teamTypeId = i.ID;
  string levelName = i.name;

  teamLevels.parentLevelId = topLevelId;
  teamLevels.name = levelName;
  teamLevels.status = Convert.ToInt32("1"); //active
  teamLevels.DateCreated = DateTime.Now;

  _db.TeamsLevels.Add(teamLevels);

  teamLevels.team = team; //add the team id foreign key

  _db.SaveChanges(); //second foreach rotation creates error

  int newItemId = teamLevels.ID; //get last item id

  IQueryable<TeamLevelRoleType> roleType = from p in _db.TeamsLevelRoleTypes
  where p.teamLevelType.ID == teamTypeId
  orderby p.orderId descending
  select p;

  TeamLevelRoleType[] roleTypeArray = roleType.ToArray();

  foreach (TeamLevelRoleType c in roleTypeArray)
  {
  string roleName = c.name;

  teamLevelRoles.name = roleName;
  teamLevelRoles.status = Convert.ToInt32("1"); //active

  _db.TeamsLevelRoles.Add(teamLevelRoles);

  teamLevelRoles.team = team; //add the team id foreign key

  checkTeamLevels = _db.TeamsLevels.Find(newItemId);
  teamLevelRoles.teamLevel = checkTeamLevels; //add the level id foreign key

  _db.SaveChanges();
  }
  }

on the second "foreach" rotation i get this error:
"An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details."

"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."

This is the row:
_db.SaveChanges(); //second foreach rotation creates error

Please note, if i disable this rows code is running fine:
checkTeamLevels = _db.TeamsLevels.Find(newItemId);
  teamLevelRoles.teamLevel = checkTeamLevels; //add the level id foreign key


What am i doing wrong?
Please advise