首页 > 解决方案 > 如何解决“DataSet 不支持 System.Nullable<>.”?

问题描述

我的目标是使用水晶报表和实体框架将数据导出到 pdf 文件,但不幸的是,当我尝试运行我的代码时收到此错误消息。

'System.NotSupportedException: 'DataSet 不支持 System.Nullable<>。'

任何人都可以请帮助我吗?

这是我迄今为止在我的控制器方面尝试过的

using System.Data.Entity;
using System.IO;
using Final_INF271.Reports;
using CrystalDecisions.CrystalReports.Engine;

public ActionResult Export()
{
    ReportDocument rd = new ReportDocument();
    rd.Load(Path.Combine(Server.MapPath("~/Reports/OutstandingOrders.rpt")));
    rd.SetDataSource(db.ProductOrder.Select(p => new
    {
        p.OrderID,
        p.Date,
        p.SupplierID,
        p.CostPrice,
        p.Quantity
    }).ToList());
    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", "OutstandingOrders");
}

包括我的 ProductOrder

namespace Final_INF271.Models
{
    using System;
    using System.Collections.Generic;

    public partial class ProductOrder
    {
        public int OrderID { get; set; }
        public Nullable<System.DateTime> Date { get; set; }
        public Nullable<int> EmployeeID { get; set; }
        public Nullable<int> SupplierID { get; set; }
        public int ProductTypeID { get; set; }
        public Nullable<decimal> CostPrice { get; set; }
        public Nullable<int> Quantity { get; set; }

        public virtual Employee Employee { get; set; }
        public virtual ProductType ProductType { get; set; }
        public virtual Supplier Supplier { get; set; }
    }
}

下面是数据集和错误消息的图片

在此处输入图像描述

标签: asp.netasp.net-mvcentity-framework

解决方案


Crystal Reports 的SetDataSource()方法创建DataColumn由列表提供ProductOrder,然后尝试构建DataColumn具有可为空类型的实例,这是不受支持的。

您应该创建一个具有相同基类型但不存在可为空类型的属性的视图模型类,然后将该类作为数据源投影结果:

// Viewmodel
public class ProductOrderVM
{
    public int OrderID { get; set; }
    public DateTime Date { get; set; }
    public int SupplierID { get; set; }
    public decimal CostPrice { get; set; }
    public int Quantity { get; set; }
}

// Controller action
rd.SetDataSource(db.ProductOrder.Select(p => new ProductOrderVM
{
    OrderID = p.OrderID,
    Date = p.Date.GetValueOrDefault(),
    SupplierID = p.SupplierID.GetValueOrDefault(),
    CostPrice = p.CostPrice.GetValueOrDefault(),
    Quantity = p.Quantity.GetValueOrDefault()
}).ToList());

或者,如果可空属性具有空值,则使用空合并/三元运算符根据其基本类型分配默认值:

rd.SetDataSource(db.ProductOrder.Select(p => new
{
    OrderID = p.OrderID,

    // with ternary operator
    Date = p.Date == null ? DateTime.MinValue : p.Date, // or DateTime.Now as default value

    // with null-coalescing operator
    SupplierID = p.SupplierID ?? 0,
    CostPrice = p.CostPrice ?? 0,
    Quantity = p.Quantity ?? 0
}).ToList());

推荐阅读