在iQueryable

时间:2016-12-09 12:20:40

标签: c# entity-framework linq

鉴于此表:

enter image description here

我需要更新所有4行的费率和平均值。

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

2 个答案:

答案 0 :(得分:1)

简单的方法是:

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

答案 1 :(得分:1)

也许你可以使用IEnumerable。

var currencies = Context.Set<Currency>().Select(c => c);
// var currencies = Context.Set<Currency>()Where(c => somecondition(c));

foreach(var c in currencies.ToList())
{
    c.Rate = ComputeRate(c);
    c.Average = ComputeAverage(c);
}

Context.SaveChanges();