12

有人知道如何将 Crystal Reports 与 Linq to SQL 一起使用吗?

4

4 回答 4

4

您可以将您的 LINQ 结果集转换为 a List,您不必严格使用 aDataSet作为报表SetDataSource,您可以提供带有 a 的 Crystal Reports 数据IEnumerable。由于List继承自IEnumerable您可以将报表的数据源设置为列表,因此您只需.ToList()在 LINQ 结果集上调用该方法。基本上:

        CrystalReport1 cr1 = new CrystalReport1();

        var results = (from obj in context.tSamples
                      where obj.ID == 112
                      select new { obj.Name, obj.Model, obj.Producer }).ToList();

        cr1.SetDataSource(results);
        crystalReportsViewer1.ReportSource = cr1;
于 2011-10-07T19:01:35.613 回答
2

msdn doc建议您可以将 Crystal Report 绑定到 ICollection 。

我可以推荐一个 List(T) 吗?

于 2008-09-19T03:28:43.287 回答
1

尽管我自己没有尝试过,但似乎可以通过结合使用 DataContext.LoadOptions 使其渴望接受关系和 GetCommand(IQueryable) 返回一个保留关系的 SQLCommand 对象。

在MSDN 论坛上查看更多信息。

于 2008-09-19T03:10:08.493 回答
0

如果您有 dbnull 值,上述代码将无法在 Web 应用程序中运行。您必须将结果列表对象转换为数据集或数据表。没有内置的方法。我遇到了同样的问题,经过数小时在互联网上的探索,我找到了解决方案,并想在这里分享以帮助任何人坚持下去。你必须在你的项目中创建一个类:-

 public class CollectionHelper
    {
        public CollectionHelper()
        {
        }

        // this is the method I have been using
        public DataTable ConvertTo<T>(IList<T> list)
        {
            DataTable table = CreateTable<T>();
            Type entityType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (T item in list)
            {
                DataRow row = table.NewRow();

                foreach (PropertyDescriptor prop in properties)
                {
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                }

                table.Rows.Add(row);
            }

            return table;
        }

        public static DataTable CreateTable<T>()
        {
            Type entityType = typeof(T);
            DataTable table = new DataTable(entityType.Name);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (PropertyDescriptor prop in properties)
            {
                // HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
            prop.PropertyType) ?? prop.PropertyType);
            }

            return table;
        }
    }

在这里设置你的水晶报告

CrystalReport1 cr1 = new CrystalReport1();

            var results = (from obj in context.tSamples
                           where obj.ID == 112
                           select new { obj.Name, obj.Model, obj.Producer }).ToList();
            CollectionHelper ch = new CollectionHelper();
            DataTable dt = ch.ConvertTo(results);
            cr1.SetDataSource(dt);
            crystalReportsViewer1.ReportSource = cr1;
于 2014-05-27T06:20:18.503 回答