繁体   English   中英

使用实体框架链接表运行更新语句

[英]Run Update Statement Using Entity Framework Linked Table

使用 EF Core 控制台应用程序,我需要让管理员用户能够 select 一个复选框,然后按下按钮,基本上运行这个伪代码语句

update EF Table set active = 'Yes' where userID = userID of checkbox

我用 EF 运行Select没有问题,但如何进行更新?

编辑
我目前有这种语法

foreach ((int Id, DateTime? submissionDate, string status) tuple in apiData)
{
    if (ctx.Test.Any(x => x.OrderId == tuple.Id))
    {
        Test ts = new Test();
        ts.Status = tuple.status;
        ctx.Test.Add(ts);
        ctx.SaveChanges();
    }
    else
    {
        Test ts = new Test();
        ts.OrderId = tuple.Id;
        ts.PdfDownloaded = tuple.submissionDate;
        ts.Status = tuple.status;
        ctx.Test.Add(ts);
        ctx.SaveChanges();
    }
}

但是当我运行代码时,我在更新(if)时收到此错误。

System.InvalidOperationException:“无法跟踪实体类型“Test”的实例,因为已经在跟踪具有相同键值 {'OrderId'} 的另一个实例。 附加现有实体时,请确保仅附加一个具有给定键值的实体实例。 考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。

编辑 2
我也尝试过这种方法

var records = ctx.Test.Where(x => x.OrderId == tuple.Id);
records.ForEach(x => x.Status = tuple.status);
ctx.SaveChanges();

但我在foreach上得到了这个编译错误

“IQueryable”不包含“ForEach”的定义,并且找不到接受“IQueryable”类型的第一个参数的可访问扩展方法“ForEach”(您是否缺少 using 指令或程序集引用?)

您应该首先获取要更新的记录

var records = context.EFTable.Where(x => x.userID == UserId).ToList();

然后你应该在所有这些对象上将 active 设置为 yes

records.ForEach(x => x.active = "yes");

最后,保存所有更改

context.saveChanges();

还将 SaveChanges 置于循环之外

var entity = context.table.WHERE(userId == checkBox).FirstOrDefault();

entity.property = "value"
context.saveChanges();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM