ObjectSet .AddObject()与EntityCollection .Add()
假设我有两个EntitySets,“Teams”和“Players”。
我正在为系统添加新的团队,为了争论,让我说我从一个文件中添加了一千个团队(包含重复项)。
该系统包含100个团队开始。 我的目标是避免重复,而不为每个添加的团队调用SaveChanges()。
该过程是查询newteam尚不存在,然后添加新团队(如果不存在)。
var team = (from t in context.Teams where t.Name == newTeam.Name select t).FirstOrDefault(); if (team==null) --Add New Team
如果我使用context.Teams.AddObject(newTeam);
添加context.Teams.AddObject(newTeam);
或context.AddObject("Teams",newTeam);
team.Count()将保持为100,如果再次运行查询,var团队将为null。
但是,如果我改为使用player.Teams.Add(newTeam);
添加团队,一切都很完美,除了我必须有一个玩家添加NewTeam,该玩家将成为所有新团队的成员。
在调用player.Teams.Add(newTeam);
该查询将返回新团队。
var team = (from t in player.teams where t.Name = newTeam.Name select t).FirstOrDefault();
player.Teams.Count()
会增加一个。
在第一个示例context.Teams是一个ObjectSet,
而在player.Teams.Add Teams是一个EntityCollection
。 我认为这些行为会相同,但事实并非如此。
有没有办法让ObjectSet
表现得像EntityCollection
? 我想在从文件中添加所有团队之后只调用一次SaveChanges。
还是有更好的方式,我没有看到?
谢谢!
没有办法让它们表现得一样。 ObjectSet
表示数据库查询,一旦您使用它,您始终会查询尚未出现新团队的数据库。 EntityCollection
是已加载实体的本地集合,如果您使用它,则会对应用程序内存进行查询。
通常使用EntityCollection
与维护单独的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();
您还可以使用Dictionary
并获得更好的性能,而不是搜索每个团队的列表。
“如果我使用context.Teams.AddObject(newTeam);或context.AddObject(”Teams“,newTeam)添加;
team.Count()将保持为100,如果再次运行查询,var团队将为null。“
在调用SaveChanges()方法之前,不会添加团队。
我猜测通过添加到Player表Navigation属性,它实际上是在调用SaveChanges()方法之前写入Team表。
我会考虑将所有新的团队放在一个列表中,然后在该列表上运行一个独特的团队。 也许是这样的……
//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();