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 a file (which contains duplicates).
The system contains 100 teams to start. And my goal is to avoid duplicates without calling SaveChanges() for every team added.
The process is to query that the newteam doesn’t already exist, Then add the new team if not exist.
var team = (from t in context.Teams
where t.Name == newTeam.Name
select t).FirstOrDefault();
if (team==null)
--Add New Team
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.
However, If I instead use player.Teams.Add(newTeam); to add the team, everything works perfectly, except I have to have a player to add the NewTeam to and that player will be a member of all new teams.
After calling player.Teams.Add(newTeam);
The query will return the new team.
var team = (from t in player.teams
where t.Name = newTeam.Name
select t).FirstOrDefault();
player.Teams.Count() will increase by one.
In the first example context.Teams is an ObjectSet<T>, whereas, in player.Teams.Add Teams is an EntityCollection<T>. I would think these would behave the same, but they do not.
Is there a way to make the ObjectSet<T> behave like the EntityCollection<T>? I want to call SaveChanges once and only once after all teams have been added from the file.
Or is there a better way that I am not seeing?
Thanks!
No there is no way to make them behave the same.
ObjectSetrepresents database query and once you use it you are always doing query to the database where your new team is not present yet.EntityCollectionis local collection of loaded entities and if you use it you are doing query to your application memory.Generally using
EntityCollectionis exactly same as maintaining separateList<Team>:You can also use
Dictionary<string, Team>and get probably better performance instead of searching the list for each team.