Search code examples
c#reportviewerdapper

Report Viewer X Dapper


I'm feeding a ReportDataSource with a query using Dapper. However, I have an empty report, even with an IEnumerable loaded data. When you spend a Datatable works.

How do I pass data from a query using Dapper for ReportViewer?

this.reportViewer.LocalReport.DataSources.Clear(); 
DataTable dt = new DataTable(); 

dt = CN.Query(Sql, param);

Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(dt.TableName, dt); 
this.reportViewer.LocalReport.DataSources.Add(rprtDTSource); 
this.reportViewer.RefreshReport(); –

Solution

  • Looks like Dapper now supports the DataTable...

    From the test:

    public void ExecuteReader()
    {
        var dt = new DataTable();
        dt.Load(connection.ExecuteReader("select 3 as [three], 4 as [four]"));
        dt.Columns.Count.IsEqualTo(2);
        dt.Columns[0].ColumnName.IsEqualTo("three");
        dt.Columns[1].ColumnName.IsEqualTo("four");
        dt.Rows.Count.IsEqualTo(1);
        ((int)dt.Rows[0][0]).IsEqualTo(3);
        ((int)dt.Rows[0][1]).IsEqualTo(4);
    }
    

    Also now supported is using a DataTable as a TableValueParameter:

    public void DataTableParameters()
    {
        try { connection.Execute("drop proc #DataTableParameters"); } catch { }
        try { connection.Execute("drop table #DataTableParameters"); } catch { }
        try { connection.Execute("drop type MyTVPType"); } catch { }
        connection.Execute("create type MyTVPType as table (id int)");
        connection.Execute("create proc #DataTableParameters @ids MyTVPType readonly as select count(1) from @ids");
    
        var table = new DataTable { Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } };
    
        int count = connection.Query<int>("#DataTableParameters", new { ids = table.AsTableValuedParameter() }, commandType: CommandType.StoredProcedure).First();
        count.IsEqualTo(3);
    
        count = connection.Query<int>("select count(1) from @ids", new { ids = table.AsTableValuedParameter("MyTVPType") }).First();
        count.IsEqualTo(3);
    
        try
        {
            connection.Query<int>("select count(1) from @ids", new { ids = table.AsTableValuedParameter() }).First();
            throw new InvalidOperationException();
        } catch (Exception ex)
        {
            ex.Message.Equals("The table type parameter 'ids' must have a valid type name.");
        }
    }