我遇到了一个问题,我似乎陷入了数据冲突。我正在尝试使用NuGet Canducci EXCEL来帮助我创建一个excel文件。如果没有返回数据,我需要取消.ToList()
或尝试错误。如果有数据被返回,除非我有.ToList()
,否则它会出错。
因此我的代码是:
[HttpPost]
[ValidateAntiForgeryToken]
public FileContentResult Report1ToExcel(Report1ToExcelViewModel viewModel) {
byte[] fileByte = null;
using(ApplicationDbContext db = new ApplicationDbContext()) {
var report1ToExcel = (
from co in db.Company
where co.CompanyStatusId == new Guid("A91DAA0F-3ADF-E511-8265-14FEB5FBEAE8")
join cy in db.Cycle on co.CompanyId equals cy.CompanyId into cycles
from cd in cycles.OrderByDescending(cy => cy.CycleDate).Take(1).DefaultIfEmpty()
where cd.CycleDate >= viewModel.Report1ToExcelDateFrom
where cd.CycleDate <= viewModel.Report1ToExcelDateTo
orderby co.InitialContact.InitialContactType descending
select new Report1ExcelData {
CompanyName = co.CompanyName,
InitialContactType = co.InitialContact.InitialContactType,
CompanyRegion = co.Region.RegionName,
NumberOfEmployees = co.NumberOfEmployees,
IndustryType = co.Industry.IndustryName,
HowHeard = co.HowHeard.HowHeardType,
ProspectingScore = co.ProspectingScore
}
);
fileByte = report1ToExcel.ToExcelByte();
}
return File(fileByte, "application/excel", "ReportOne.xlsx");
}
最后查看fileByte =
?如果我有,
fileByte = report1ToExcel.ToExcelByte();
然后,如果返回了一个空数据集,则可以正常工作,但是如果返回了填充的数据集,则会抛出错误消息,
There is already an open DataReader associated with this Command which must be closed first.
如果我使用,
fileByte = report1ToExcel.ToList().ToExcelByte();
然后它仅在返回数据时有效。如果没有返回数据,我会收到错误消息
Enumeration has either not started or has already finished.
似乎我有一个“该死的,如果我这样做,该死的,如果我不这样”的情况。
请记住,我正在通过子表中非常具体的日期范围进行过滤,对于公司可以存在多个条目,但我想仅定位最新条目。因此.Take(1).DefaultOrEmpty()
。我需要能够处理一个日期范围可能会在数据集中带回绝对任何情况的情况。