-1

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;
demo
  • 6,038
  • 19
  • 75
  • 149
  • You're not changing any properties. Where does `history` come from and what updates do you expect to happen? – CodeCaster Feb 10 '16 at 13:50
  • And no, _"history is input parameter List"_ does not clarify that. Is this a detached entity, for example through an MVC form POST? – CodeCaster Feb 10 '16 at 13:55

1 Answers1

1

Seems that EF does not detect changes within array elements. You can however force update. Check this Entity Framework 5 Updating a Record

Community
  • 1
  • 1
  • What does _"EF does not detect changes within array elements"_ mean? Also, if you think a question is answered elsewhere, flag as duplicate, please. – CodeCaster Feb 10 '16 at 13:52
  • @CodeCaster For examle, sql type `varbinary` would be `byte[]` in EF. Changing some elements in array `byte[]` and calling `SaveChanges` will not detect that the array contents has been changed, and will not update. –  Feb 10 '16 at 13:58
  • That's right, you'll have to re-assign a a `byte[]` property on an entity or explicitly mark it as modified in order for the change tracker to pick up that change, but I don't really see how that relates to the question here. – CodeCaster Feb 10 '16 at 14:22
  • @CodeCaster maybe OP didn't put the related code to question. Code in the question is related to insert, while the question is about update. –  Feb 10 '16 at 14:28