From the sql the following error is coming , when trying to find out max number and If there is no any record on the table , then this LINQ sql error is coming 'Sequence contain bo elements' if no record the return value should be 0
public int GetMaxMeterReading(int depotno, int year,string metercode) //
{
int maxReading = (from d in ctx.goMeterReading
where d.DepotNo == depotno && d.ReadingYear == year && d.MeterCode == metercode
select d.Reading).Max();
return maxReading;
}
From the sql the following error is coming , when trying to find out max number and If there is no any record on the table , then this LINQ sql error is coming 'Sequence contain bo elements' if no record the return value should be 0
Write code to check if the LINQ query returns results.
var readings = (from d in ctx.goMeterReading
where d.DepotNo == depotno && d.ReadingYear == year && d.MeterCode == metercode
select d.Reading).ToList();
int maxReading = 0;
if(readings != null && readings.Count() > 0)
{
maxReading = readings.Max();
}
You could also insert the DefaultIfEmpty() command between the query and Max() to prevent this error:
int maxReading = (from d in ctx.goMeterReading
where d.DepotNo == depotno && d.ReadingYear == year && d.MeterCode == metercode
select d.Reading).DefaultIfEmpty(0).Max();
Best Regards,
Rena
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
411 Points
1327 Posts
Sequence contain bo elements error please help
Nov 12, 2019 04:34 PM|polachan|LINK
From the sql the following error is coming , when trying to find out max number and If there is no any record on the table , then this LINQ sql error is coming 'Sequence contain bo elements' if no record the return value should be 0
public int GetMaxMeterReading(int depotno, int year,string metercode) // { int maxReading = (from d in ctx.goMeterReading where d.DepotNo == depotno && d.ReadingYear == year && d.MeterCode == metercode select d.Reading).Max(); return maxReading; }
All-Star
53031 Points
23607 Posts
Re: Sequence contain bo elements error please help
Nov 12, 2019 05:16 PM|mgebhard|LINK
Write code to check if the LINQ query returns results.
Contributor
2690 Points
874 Posts
Re: Sequence contain bo elements error please help
Nov 13, 2019 04:31 AM|Rena Ni|LINK
Hi polachan,
You could also insert the DefaultIfEmpty() command between the query and Max() to prevent this error:
int maxReading = (from d in ctx.goMeterReading where d.DepotNo == depotno && d.ReadingYear == year && d.MeterCode == metercode select d.Reading).DefaultIfEmpty(0).Max();
Best Regards,
Rena
Member
411 Points
1327 Posts
Re: Sequence contain bo elements error please help
Nov 13, 2019 08:59 AM|polachan|LINK
Many Thanks to all