[英]ASP.NET MVC is throwing an error while doing aggregation - can anyone help me?
enter image description here在此处输入图像描述
enter image description here在此处输入图像描述
I have a scoreboard.我有一个记分牌。 In this table, when users make a transaction, the score is recorded with that user's id.
在此表中,当用户进行交易时,分数会与该用户的 id 一起记录。 But someone who is a new member of the site gives the above error because they do not have any data in this table.
但是该站点的新成员给出了上述错误,因为他们在此表中没有任何数据。 It can add users with data in the table, but it gives an error when a new user becomes a member.
它可以在表中添加具有数据的用户,但是当新用户成为成员时会出错。 How can I solve this?
我该如何解决这个问题? (I have attached the link of the error image. You can open and see)
(我附上了错误图片的链接,你可以打开看看)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectTiklaKazan.Models.Sınıf;
namespace ProjectTiklaKazan.Controllers
{
[Authorize]
public class AnaMenuController : Controller
{
Context c = new Context();
// GET: AnaMenu
public ActionResult Index()
{
Users u = Session["UserID"] as Users;
var toptohum = c.PuanBilgis.Where(x => x.UserID == u.UserID).Sum(x => x.PuanMiktar).ToString();
if (toptohum !=null)
{
TempData["toptohum"] = toptohum;
}
else
{
TempData["toptohum"] = 0;
}
return View();
}
}
}
You're hitting this issue because IEnumerable<T>
only knows that a collection has no items in it by iterating over the collection.您遇到了这个问题,因为
IEnumerable<T>
通过迭代集合只知道集合中没有项目。
In your case, c.PuanBilgis.Where(x => x.UserID == u.UserID)
yields an IEnumerable<>
that has no contents, but it doesn't know that it has no contents.在您的情况下,
c.PuanBilgis.Where(x => x.UserID == u.UserID)
产生一个没有内容的IEnumerable<>
,但它不知道它没有内容。 Then the Sum(...)
LINQ extension is called, and tries to iterate over the IEnumerable<>
, but hits an exception when it tries to read from the database and there is no data to be read.然后调用
Sum(...)
LINQ 扩展,并尝试遍历IEnumerable<>
,但在尝试从数据库中读取并且没有要读取的数据时遇到异常。
However, IList<T>
has a Count
property on it that keeps track of the number of elements in the collection.但是,
IList<T>
上有一个Count
属性,用于跟踪集合中的元素数。 So if you can convert your IEnumerable<T>
into an IList<T>
, then some of the LINQ extensions will be able to take advantage of the Count
property and save itself from the cost of enumerating the collection.因此,如果您可以将
IEnumerable<T>
转换为IList<T>
,那么一些 LINQ 扩展将能够利用Count
属性并节省枚举集合的成本。
This does have an up-front perf cost of enumerating the data entirely instead of on-demand, but it's not much, especially if the collection is empty.这确实具有完全枚举数据而不是按需枚举数据的前期性能成本,但这并不多,尤其是在集合为空的情况下。
In your case, you could do something like this:在您的情况下,您可以执行以下操作:
c.PuanBilgis.Where(x => x.UserID == u.UserID).ToList().Sum(x => x.PuanMiktar).ToString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.