Lately I’ve been quite
involved with using “Linq to Sql” in various database related .Net applications
and it’s not surprising that a time came when I needed to do some reporting. I
chose to create reports in Crystal Reports so it would be as quick and painless
as possible. I was stuck with getting the reports to work directly with my
already existing linq queries. I did not want to bust down and figure out the
usual standard way of setting up such a report. I just needed to believe that
Crystal Reports can just take a linq query and voila! All done. It turns out
that this is quite the case at least with Visual Studio 2008.
First create your aspx
web page and insert the below. You can just drag the “Crystal Report” component
from the tool box to your page:
<%@
Register Assembly="CrystalDecisions.Web,
Version=10.5.3700.0, Culture=neutral, PublicKeyToken=123456789xxxxxxxx"
Namespace="CrystalDecisions.Web"
TagPrefix="CR"
%>
.
.
.
<CR:CrystalReportViewer
ID="CrystalReportViewer1"
runat="server"
/>
<CR:CrystalReportSource
ID="CrystalReportSource1"
runat="server">
<Report
FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>
Then in your “.cs” file
create your query and assign it to the ReportDocument object of
CrystalReportSource1. Make sure you have a “Select New” and a “ToList()” so that
the report gets the data as it requires.
override protected
void OnInit(EventArgs
e)
{
var query = (
from q in
somedatabase.sometable
where d.somefield ==
"field"
select new
{ q.somefield, q.somefield2}
).ToList();
CrystalReportSource1.ReportDocument.SetDataSource(query);
}
You obviously also need to create the
Crystal Report as defined above as “CrystalReport.rpt”. The only catch is that
the report needs to know the fields defined with “Database Expert…” inside the
Crystal Reports designer. You need to have at least the fields as the output of
the linq query. You can do this with a data set or use the table from that
database, whatever works to get those fields to match the linq query.
That’s it. No problemo.