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

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

    List 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 and get probably better performance instead of searching the list for each team.

提交回复
热议问题