无法将类型'...'隐式转换为'System.Collections.Generic.IList< ...>'。存在显式转换(您是否错过了演员?)

时间:2016-06-13 17:22:10

标签: c# asp.net asp.net-mvc-4

我遇到了代码问题。我想通过ID在我的表中选择行 任何帮助都非常感激。谢谢。

public FileStreamResult GetPdf(int?  id) 
{
        IList<Requisition> all = new List<Requisition>();
        using (ClinlabEntities dc = new ClinlabEntities()) 
        {
            all = dc.Requisitions.ToList().First(ReqId => ReqId.ReqId == id); 
        }
        WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);
        string gridHtml = grid.GetHtml(
        columns: grid.Columns(
        grid.Column("FirstName", ""),
        grid.Column("LastName", " "),
            //grid.Column("AccountNo", ""),
        grid.Column("Address", ""),
        grid.Column("City", ""),
        grid.Column("State", ""),
        grid.Column("Zip", "")
        )).ToString();

        string exportData = String.Format("<html><head>{1}</head><body>{1}</body></html>", "<style>table(border-spacing:10px; border-collapse:seperate;)</style>", gridHtml);
        var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
        using (var input = new MemoryStream(bytes)) 
        {
            var output = new MemoryStream();
            var document = new iTextSharp.text.Document(PageSize.LETTER, 15, 0, 0, -15);
            var writer = PdfWriter.GetInstance(document, output);
            writer.CloseStream = false;
            document.Open();
            var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
            xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF7);
            document.Close();
            output.Position = 0;
            return new FileStreamResult(output, "Application/Pdf");
        }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您要将“申请单”列表的第一个结果分配给all变量,该变量期望List<Requisition>而不是Requisition返回的.First()

IList<Requisition> all = new List<Requisition>();
using (ClinlabEntities dc = new ClinlabEntities()) {
    all = dc.Requisitions.ToList().First(ReqId => ReqId.ReqId == id); 
}

最简单的解决方案是将all更改为预期单个记录:

 Requisition all = null;

但是,由于您实际上已将所有Requisition条记录加载到内存中并进行过滤,因此效率极低。您应该使用.FirstOrDefault()并放弃.ToList()

Requisition all = null;
using (ClinlabEntities dc = new ClinlabEntities()) {
    all = dc.Requisitions.FirstOrDefault(ReqId => ReqId.ReqId == id); 
}