0

Below is currently that i use to update the data (more than 1 record) by using EF core. How can update certain column(s) (in this case, actually I just want update CurrencyCode and UpdatedDate columns only)? Now, the only way is, reassign the value in order to update again. But this approach is not suitable if have a lot of columns.

var sorting = await _context.Media.AsNoTracking().ToListAsync();
        var redirect = await _context.Website.Where(x => x.url.Equals(url)).AsNoTracking().ToListAsync();

        var data = (from sortingData in sorting
                    join redirectData in redirect on sortingData.MediaID equals redirectData.ID
                    select new Media
                    {
                        ID = sortingData.ID,
                        Post = sortingData.Post,
                        CurrencyCode = currencyCode,
                        CreatedDate = sortingData.CreatedDate,
                        UpdatedDate = DateTime.Now
                    }).ToList();

        if (data?.Count > 0) //May have more than 1 record.
        {
            _context.Media.UpdateRange(data);
            return await _context.SaveChangesAsync() > 0;
        }
Progman
  • 16,827
  • 6
  • 33
  • 48
user3860946
  • 27
  • 1
  • 6
  • 1
    You can mark the specific properties which have been modified https://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework – Jasen Feb 11 '22 at 18:59
  • 1
    If you use EF properly, then any time you update a record that has been read, it automatically works out what has changed, and just updates those column. You are querying .AsNoTracking() which turns this off. – Neil Feb 11 '22 at 21:23
  • Does this answer your question? [How to update only one field using Entity Framework?](https://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework) – L.Vallet Feb 15 '22 at 07:47

0 Answers0