我有一个名为Drivers的表,如下所示:
ID QuoteID Name Amount
1 1 jim 100
2 1 bob 200
可能存在1行或多行具有不同PK(ID)但具有相同外键(QuoteID)的情况。在任何一种情况下,我都想抓住具有给定QuoteID的所有人,并且能够操纵每个人的“金额”下的值。
我正在使用Razor在MVC 4中工作。以下是我到目前为止在控制器中的内容:
long quoteID = model.Driver.QuoteID.Value;
var driversModel = db.Drivers.Single(g => g.QuoteID == quoteID);
//amt1 should be for jim and amt2 should be for bob
double amt1 = driversModel.Amount * 1.04;
double amt2 = driversModel.Amount * 1.05;
double total = amt1 + amt2;
有人可以向我推进正确的方向吗?我应该使用其他“.Single”来让我访问这些金额吗?
答案 0 :(得分:3)
Single()得到一排。使用Where()
获取满足查询的所有行。
IEnumerable<Drivers> driversModel = db.Drivers.Where(g => g.QuoteID == quoteID);
// SingleOrDefault - default value if that element is not found.
Driver jim = driversModel.SingleOrDefault(x => x.Name == "jim");
Driver bob = driversModel.SingleOrDefault(x => x.Name == "bob");
double jimsAmount = jim.Amount ?? 0;
double bobsAmount = jim.Amount ?? 0;
double amt1 = jimsAmount * 1.04;
double amt2 = bobsAmount * 1.05;
double total = amt1 + amt2;
// Project to a list of doubles.
List<double> amounts = driversModel.Select(x => x.Amount);
// Sum amount property on Driver.
double sum = driversModel.Sum(x => x.Amount);
答案 1 :(得分:0)
var driversModel = db.Drivers.Where( d => d.QuoteID == quoteID )
返回具有指定quoteID
然后,您需要在获得金额乘数的任何地方加入,加上.Amount
和SUM
结果。