ObjectSet.AddObject() vs. EntityCollection.Add()

后端 未结 2 596
春和景丽
春和景丽 2021-01-19 17:21

Let\'s say I have two EntitySets, \"Teams\" and \"Players\".

I am adding new teams to the system, for sake of argument, let\'s say I\'m adding a thousand teams from

2条回答
  •  [愿得一人]
    2021-01-19 18:06

    "If I add using context.Teams.AddObject(newTeam); or context.AddObject("Teams",newTeam);

    The team.Count() will remain 100 and if you ran the query again, var team would be null."

    The teams won't be added until you call the SaveChanges() method.

    I'm guessing that by adding to the Player table Navigation property it is actually writing to the Team table before the SaveChanges() method is called.

    I would consider putting all the new Teams in a List and then running a distinct on that list. Maybe something like this...

    //an array of the new teams
    var newTeams = {"Chi","Cle","La","Ny"};
    
    //a list of the teams in the database
    var teamsInDb = context.Teams.ToList();
    
    //a query to get the unique teams that are not in the database
    var uniqueTeams = newTeams.Where(t => !teamsInDb.Contains(t)).Distinct();
    
    //iterate the new teams and add them
    foreach(var t in uniqueTeams)
    {
        context.Teams.AddObject(t);
    }
    
    //save
    context.SaveChanges();
    

提交回复
热议问题