I have next code :
using (var context = new DataContext())
{
var dbHistoryItems = context.Set<HistoryItem>();
var historyItems = history as HistoryItem[] ?? history.ToArray();
var historyItemIds = historyItems.Select(c => c.Id);
var existingEntities = dbHistoryItems.Where(h => historyItemIds.Contains(h.Id));
if (existingEntities.Any())
{
var newEntities = historyItems.Where(h => !existingEntities.Select(e => e.Id).Contains(h.Id));
dbHistoryItems.AddRange(newEntities);
}
context.SaveChanges();
}
where history
is input parameter List<HistoryInfo>
When entity is new (entity with ID doesn't exist in Context) I add it to Context. When entity is existing - I just want to save it (It can be modified).
Problem in this code is with Update. It doesn't update existing entities.
UPD:
Is there best way to insert or update collection of entities then in loop like:
foreach(var item in collection)
{
db.AddOrUpdate(item);
}
db.SaveChanges;