c# - 更新 iQueryable 中的多行

标签 c# entity-framework linq

给定这张表:

enter image description here

我需要更新所有 4 行的 Rate 和 Average。

var currency = Context.Set<Currency>().Select(c => c);

这将创建 currency 作为 iQueryable。但现在我无法设想如何制定更新语句来更新所有四行中的 RateAverage

我需要做的是等价于此:

update Currencies set rate = 1.7, Average = 1.1 where CurrencyId = 1
update Currencies set rate = 2.5, Average = 2.1 where CurrencyId = 2
update Currencies set rate = 3.1, Average = 3.1 where CurrencyId = 3
update Currencies set rate = 42.7, Average = 42.1 where CurrencyId = 4

最佳答案

简单的方法是:

var currency1 = Context.Currency.Find(1);
curreny1.Rate = 1.7;
currency1.Average = 1.1;
//do the same for other currencies and finally save changes
Context.SaveChanges();

如果您想避免对数据库进行额外的 GET 调用以使用 id 获取货币对象,则

var currency1 = new Currency{CurrenyId = 1, Rate = 1.7, Average = 1.1 };   

var entry1 = Context.Entry(currency1);
entry1.Property(p=> p.Rate).IsModified = true;
entry1.Property(p=> p.Average).IsModified = true;

Context.SaveChanges();

关于c# - 更新 iQueryable 中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41060377/

相关文章:

c# - javascript 是否等效于 C#s HttpUtility.HtmlEncode?

asp.net-mvc - EF Code First 和确认字段

entity-framework - DbContext 在长时间运行的进程中的生命周期

c# - 如何在查询 C# 中使用 Linq 和 Dictionary 从 List<> 获取元素?

c# - 从 LINQ 实体中的日期时间获取可排序字符串的正确方法是什么?

c# - 带有 linq .where 子句的空引用异常

c# - 显示数据库中的数据

c# - 如何访问 Azure API 管理中设置变量策略中的请求正文?

c# - 如何从我的 C# 应用程序中检查新 Microsoft Edge Chromium 的版本?

c# - 为什么使用存储库模式或者请向我解释一下?