Skip to main content
 首页 » 编程设计

c#之使用 LINQ 更新多行的多列

2024年02月13日11lhb25

我正在使用 Entity 框架构建应用。

要更新的表。

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

类:

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){ 
 
} 

如何使用 LINQ 使用来自前端的列表中的值来更新表的多列(如(选中,评论))?

请您参考如下方法:

假设 dbContext 是您的 DataContext 并且 Id 是表的主键,试试这个:

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(); 
}