我使用EF有以下结构:
“事件”有很多“宾客”
假设Event.Guests有4个Guest元素,id为1,2,3,4 我想更新Event.Guests以使访客的ID为3,4,5(如果Guest 5不存在,我想创建它)。
从Event中删除现有guest虚拟机并添加新guest虚拟机的最有效方法是什么?
这就是我现在正在做的事情:
var newGuests = new List<Guest>();
var existingGuests = @event.Guests.ToList();
// GetNewGuestsIds will return the new guests list (3,4,5)
foreach (var guestId in GetNewGuestsIds())
{
Guest guest = existingGuests.FirstOrDefault(eg => eg.Id == guestId);
if (guest == null)
{
guest = db.Guests.CreateObject();
// fill guest data here
}
newGuests.Add(guest);
}
foreach (var existingGuest in existingGuests)
{
// Remove the existing element from the list to add
var removed = newGuests.RemoveAll(g => g.Id == existingGuest.Id);
if (removed == 0) // The existing host is not on the list to add, delete it
{
@event.EventHosts.Remove(existingGuest);
}
}
foreach (var guest in newGuests)
{
@event.Guests.Add(guest);
}
但我认为这可能会有所改善......我只是不知道如何。
谢谢!
答案 0 :(得分:0)
经过一番思考后我得到了这个看起来好多了的结果:
var existingGuests = @event.Guests.ToList();
// GetNewGuestsIds will return the new guests list (3,4,5)
foreach (var guestId in GetNewGuestsIds())
{
if (existingGuests.RemoveAll(g => g.Id == guestId) == 0)
{
guest = db.Guests.CreateObject();
// fill guest data here
@event.Guests.AddObject(guest);
}
}
existingGuests.ForEach(g => @event.Guests.Remove(g));
我希望这有助于其他人。