序列不包含任何元素错误
本文关键字:元素 错误 何元素 包含任 | 更新日期: 2023-09-27 18:31:26
>我的数据库结构如下
学生注册表
Id Name
5 Sachin
学生收据表
Id StudRegId Fee ST Total Status DueDate
1 5 873 127 1000 1 01/05/2016
2 5 873 127 2000 1 01/15/2016
3 5 873 127 3000 0 01/25/2016
4 5 873 127 4000 0 01/28/2016
5 5 873 127 5000 0 01/30/2016
状态指示付款方式。状态 1 表示学生已支付收据,0 表示未付款收据
查询
_dTableReg = _db.StudentRegistrations
.AsEnumerable()
.Where(r => (..condition))
.Select(r => new RegistraionVM.RegDataTable
{
...
...
NextDueAmount = r.StudentReceipts.
Where(rc => rc.Status == false)
.First().Total.ToString(),
NextDueDate = r.StudentReceipts.
Where(rc => rc.Status == false)
.First().DueDate.Date.ToString('dd/MM/yyyy')
}).OrderByDescending(r => r.RegistrationID).ToList();
上面的查询返回第一个未付金额和日期(3000 & 01/25/2016)。
当学生支付了所有收据(即状态将设置为 1)并且我得到Sequence contains no elements errror
时,就会出现问题。在这种情况下,我想在NextDueAmount
和NexDueDate
中返回FULL PAID
注册表数据表类
public class RegDataTable
{
...
...
public string NextDueAmount { get; set; }
public string NextDueDate { get; set; }
}
您使用.First()
会抛出错误是StudentReceipt
的集合不返回任何项目(即当所有项目的Status
为true
时)。您需要使用 .FirstOrDefault()
然后检查该值是否为 null
,如果不是,则访问 Total
和 DueDate
属性。
这可能会使控制器代码变得不必要地复杂(并且您还访问数据库两次以获取集合),因此我建议您使用具有其他只读属性的视图模型(如果尚未访问)来返回结果
public class RegDataTableVM
{
....
public StudentReceipt Receipt { get; set; }
public string NextDueAmount
{
get { return Receipt == null ? "FULL PAID" ? Receipt.Total.ToString() }
}
public string NextDueDate
{
get { return Receipt == null ? "FULL PAID" ? Receipt.DueDate.ToString("dd/MM/yyyy") }
}
并将查询修改为
_dTableReg = _db.StudentRegistrations
.Where(r => (..condition))
.Select(r => new RegDataTableVM
{
...
...
Receipt = r.StudentReceipts.Where(rc => rc.Status == false).FirstOrDefault()
}).OrderByDescending(r => r.RegistrationID).ToList();
旁注:如果您使用DisplayFor()
生成 html,您也可以使用DisplayFormatAttribute
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", NullDisplayText = "FULL PAID"
public DateTime? NextDueDate
{
get { return return Receipt == null ? null ? Receipt.DueDate }
}