基本上我有一个带有支出和收益的模型BalanceUsers和一个日期列,我想要的是查询该表并按日期升序排序所有行,我需要这样做以便我可以在startDate和endDate之间进行搜索我从表格发送以获得在这两个日期之间限制的价值,但没有任何反应可能我做错了。
这就是我做的
[HttpPost]
public ActionResult Index(string startDate, string endDate)
{
DateTime data1 = DateTime.Parse(startDate);
DateTime data2 = DateTime.Parse(endDate);
var userId = User.Identity.GetUserId();
decimal gastos = 0;
decimal rendimentos = 0;
var orderDates = db.BalanceUsers.Where(d => d.ApplicationUserId == userId).OrderBy(d => d.data); //this is what does the job
var lowestValue = orderDates.Where(d => d.ApplicationUserId == userId).Min(d => d.valor);
var BiggestDate = orderDates.Where(d => d.ApplicationUserId == userId).First(d => d.valor == lowestValue);
var dateBiggestDate = BiggestDate.data;
var biggestValue = orderDates.Where(d => d.ApplicationUserId == userId).Max(d => d.valor);
var biggestDate2 = orderDates.Where(d => d.ApplicationUserId == userId).First(d => d.valor == biggestValue);
var biggestDateEarning = biggestDate2.data;
foreach (var balance in orderDates.Where(d => d.ApplicationUserId == userId))
{
if(balance.valor < 0)
{
expenses += balance.valor;
}
else
{
earnings += balance.valor;
}
}
statistic model = new statistic()
{
utilizador = User.Identity.GetUserName(),
gastos = gastos,
rendimentos = rendimentos,
maiorValorDespesa = lowestValue,
dataMaiorDespesa = dataMaiorDespesa,
dataMaiorRendimento = dataMaiorRendimento,
maiorValorRendimento = biggestValue,
};
return View(modelo);
在我的视图中,我只显示传递给我的modelView的数据,所以我不认为问题出在视图上。
PS:抱歉我的英文不好
答案 0 :(得分:0)
For next time or if you want more help
That said I looked at your code and it seems you can do everything in there with just 1 call. Also no where in your code do you actually make use of those dates that are passed in. Also why are you not passing them in as actual DateTime
objects?
var highestLowestValors = db.BalanceUsers.Where(d => d.ApplicationUserId == userId)
.GroupBy(x => x.ApplicationUserId)
.Select(x => new {
biggestValor = x.Max(y => y.valor),
lowestValor = x.Min(y => y.valor),
expenses = x.Where(y => y.valor < 0).Sum(y => y.valor),
earnings = x.Where(y => y.valor > 0).Sum(y => y.valor),
}).Single();
i need to do that soo i can search between a startDate and an endDate
First Sql is a declaritive language. This means you do not need to order the data and then loop through it to get what you need. Instead declare that you only want data between those 2 dates. Lets say your date column for your table BalanceUsers
is called OccurredOn
, you would change the query like so.
DateTime startDateSearch, endDateSearch; // assign these values somewhere
var highestLowestValors = db.BalanceUsers.Where(d => d.ApplicationUserId == userId && d.OccurredOn >= startDateSearch && d.OccurredOn <= endDateSearch)
.GroupBy(x => x.ApplicationUserId)
.Select(x => new {
biggestValor = x.Max(y => y.valor),
lowestValor = x.Min(y => y.valor),
expenses = x.Where(y => y.valor < 0).Sum(y => y.valor),
earnings = x.Where(y => y.valor > 0).Sum(y => y.valor),
}).Single();