Bulk updates using linq entities

143 views Asked by At

I have a list of object like List category has properties, CategoryId, CategoryName, Categorymessage,

I have to use this list to update records in the database table Categories, which has the same columns CategoryId, CategoryName, CategoryMessage for the items in list which have a matching CategoryId as in the database table

How can I do that as a bulk update, using Entity framework extensions, the examples I saw have the update value hard coded like below, (statusId =2), whereas for me that value has to be retrieved from the item in the list which matches the categoryId in the database table.

 context.Tasks.Update(
t => t.StatusId == 1, 
t => new Task {StatusId = 2});

Thanks in advance.

1

There are 1 answers

1
HashCoder On

I am not sure whether this what you are looking for? I haven't run this code.

 List<Category> categoryList = new List<Category> {
                        new Category { Id = 1, Message = "A", Name = "A"},
                        new Category { Id = 2, Message = "B", Name = "B"},
                        new Category { Id = 3, Message = "C", Name = "C"},
                        new Category { Id = 4, Message = "D", Name = "D"},
                };
        using (var container = new Model1Container())
        {
           IQueryable<Category> categoryQueryable = container.Categories.Where(x => categoryList.Any(t => t.Id == x.Id));
           foreach (Category item in categoryQueryable)
           {
               var categorySource = categoryList.Where(x => x.Id == item.Id).Select(m => m).FirstOrDefault();
               item.Message = categorySource.Message;
               item.Name = categorySource.Message;
           }

                container.SaveChanges();
        }