none
Best way to update/insert items in an existing collection? RRS feed

  • Question

  • Hi,

    I am new to EF(6). That said, I have the following use case:

    Stock quotes are given to a method which shall persist these quotes. Existing quotes shall be udpated. New quotes shall be inserted. I solved this by loading the existing quotes and then determining if the passed quotes are new or not. If not, I update the corresponding existing quote. Otherwise, I add the none existing quote to the DbSet.

    Does a better solution exist, eg. some kind of EF-merge-function?

    Here is the code (note: Security object omitted for simplicity):

            /// <summary>
            /// Saves or updates the historic quotes.
            /// </summary>
            /// <param name="historicQuotes">The historic quotes.</param>
            public void SaveHistoricQuotes(IEnumerable<HistoricQuote> historicQuotes)
            {
                using (var dbContext = new DividendsManagerEntities())
                {
                    var existingQuotes = dbContext.HistoricQuote.ToList();
    
                    // update existing quotes
                    foreach (var existingQuote in existingQuotes)
                    {
                        var newQuote = historicQuotes.SingleOrDefault(q => q.Date == existingQuote.Date);
    
                        if (newQuote != null)
                        {
                            existingQuote.Close = newQuote.Close;
                        }
                    }
    
                    // add new quotes
                    foreach (var newQuote in historicQuotes)
                    {
                        if (!existingQuotes.Any(q => q.Date == newQuote.Date))
                        {
                            dbContext.HistoricQuote.Add(newQuote);
                        }
                    }
    
                    dbContext.SaveChanges();
                }
            }
    Thank you!



    Tuesday, May 12, 2015 4:48 PM

Answers

  • Does a better solution exist, eg. some kind of EF-merge-function?

    No, and what you are doing is typical and is the way to do it.

    Tuesday, May 12, 2015 5:37 PM

All replies

  • Does a better solution exist, eg. some kind of EF-merge-function?

    No, and what you are doing is typical and is the way to do it.

    Tuesday, May 12, 2015 5:37 PM
  • Hi,

    thanks for your answer. Then I will proceed as I aldready did.

    Regards,

    Torsten

    Wednesday, May 13, 2015 7:31 AM