Crystal Report

时间:2016-01-28 06:36:39

标签: c# asp.net crystal-reports

我正在使用asp.net mvc 4Crystal Report来创建数据存储在MSSQL数据库中的收据,用户可以将收据下载为pdf文件。出于某种原因,每次我尝试下载时,都会收到错误,

  

CrystalDecisions.CrystalReports.Engine.DataSourceException:数据源对象无效。

以下是代码,

    public ActionResult ExtractReceipt()
    {
        var getOwner = rentdb.OwnerRegs.Where(a => a.username == User.Identity.Name).FirstOrDefault();
        var getId = getOwner.serial;

        ReportDocument rd = new ReportDocument();
        rd.Load(Path.Combine(Server.MapPath("~/Reports/Invoice.rpt")));
        rd.SetDataSource(rentdb.Invoices.Where(a => a.owner_id == getId).FirstOrDefault());
        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();
        Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        stream.Seek(0, SeekOrigin.Begin);
        return File(stream, "application/pdf", "MyReceipt.pdf");
    }

我的代码有什么问题吗?我该如何解决这个问题?感谢。

2 个答案:

答案 0 :(得分:2)

请试试这个

 var query=rentdb.Invoices.Where(a => a.owner_id == getId).FirstOrDefault();

 var querylist = new List<Invoices> { query };

 rd.SetDataSource(querylist);

答案 1 :(得分:0)

您需要将FirstOrDefault()更改为ToList();

public ActionResult ExtractReceipt()
{
    var getOwner = rentdb.OwnerRegs.Where(a => a.username == 
    User.Identity.Name).FirstOrDefault();
    var getId = getOwner.serial;

    ReportDocument rd = new ReportDocument();
    rd.Load(Path.Combine(Server.MapPath("~/Reports/Invoice.rpt")));
    rd.SetDataSource(rentdb.Invoices.Where(a => a.owner_id == getId).ToList()); //FirstOrDefault() Need To Change
    Response.Buffer = false;
    Response.ClearContent();
    Response.ClearHeaders();
    Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
    stream.Seek(0, SeekOrigin.Begin);
    return File(stream, "application/pdf", "MyReceipt.pdf");
}