ankur
ankur

Reputation: 4733

Update Multiple columns of multiple rows using LINQ

I am using Entity framework for building an app.

Table to be updated.

[Id] [CheckItemId]  [Checked]  [Comment]
1      100             1          abc
2      150             0          xyz

Class:

public class CheckListRequest
{
    public int ID { get; set; }
    public bool IsChecked { get; set; }
    public string Comment { get; set; }
}

public static void UpdateCheckList(List<CheckListRequest> checkList){

}

How do I update the table multiple column like (Checked,comment) with the values coming in list from frontend using LINQ?

Upvotes: 1

Views: 6037

Answers (4)

Dharmender Tongar
Dharmender Tongar

Reputation: 46

You can use ForEachAsync or ForEach like below

var actionTakenOnEndorsement = _context.Endorsement.Where(x => x.IsDeleted == false && x.IsApproved != null).OrderBy(o => o.SolutionId).ThenByDescending(o => o.ModifiedOn).DistinctBy(x => new { x.SolutionId, x.UserId }).AsQueryable();
                
await actionTakenOnEndorsement.ForEachAsync(x => { x.IsEndorsementRevoked = true; x.Comment = "Revoked by system"; });

Upvotes: 0

ekad
ekad

Reputation: 14624

Assuming dbContext is your DataContext and Id is the primary key of the table, try this:

public static void UpdateCheckList(List<CheckListRequest> checkList)
{
    foreach (CheckListRequest clr in checkList)
    {
        CheckListRequest clrInDB = dbContext.CheckListRequests.SingleOrDefault(o.Id == clr.Id);
        clrInDB.IsChecked = clr.IsChecked;
        clrInDB.Comment = clr.Comment;
    }

    dbContext.SaveChanges();
}

Upvotes: 6

Girish Vadhel
Girish Vadhel

Reputation: 745

You can use foreach loop on your list as below:

public static void UpdateCheckList(List<CheckListRequest> checkList)
{
    checkList.foreach(CL =>{
              CheckListRequest objCLR= DataContext.CheckListRequests
              .SingleOrDefault(E => E.Id == CL.Id);
        objCLR.IsChecked = CL.IsChecked;
        objCLR.Comment = CL.Comment;
        });

    DataContext.SaveChanges();
}

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

How do I update the table multiple column like (Checked,comment) with the values

Exactly the same way you'd update only one column...

  1. Get the entity from context
  2. Update column/columns
  3. Call SaveChanges() method on context.
using(var ctx = new MyContext())
{
    var entity = ctx.Table.First(t => t.Id == myId);
    entity.Prop1 = "newValue";
    entity.Prop2 = 23;

    ctx.SaveChanges();
}

Upvotes: 0

Related Questions