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

后端 未结 2 597
春和景丽
春和景丽 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 17:48

    No there is no way to make them behave the same. ObjectSet represents database query and once you use it you are always doing query to the database where your new team is not present yet. EntityCollection is local collection of loaded entities and if you use it you are doing query to your application memory.

    Generally using EntityCollection is exactly same as maintaining separate List<Team>:

    List<Team> teams = context.Teams.ToList();
    
    var team = teams.FirstOrDefault(t => t.Name == newTeam.Name);
    if (team == null) 
    {
        context.Teams.AddObject(newTeam);
        teams.Add(newTeam);
    }
    
    context.SaveChanges();
    

    You can also use Dictionary<string, Team> and get probably better performance instead of searching the list for each team.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题