asp.net - 如何解决“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; }
}
}
下面是数据集和错误消息的图片
解决方案
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());
推荐阅读
- xamarin.forms - 为什么在使用 ReactiveContentPage 时会出现“不一致的可访问性”问题?
- java - 尝试从输入流(逐个字符)将单词解析为 HashMap,但是,空格不断出现?
- react-native - 如何从 React Native 中的不同组件调用方法
- android - IronSource 奖励视频加载
- c# - 我正在尝试让人工智能跟随一条路径,但它不起作用
- android - 有没有办法使用同一个lib的2个不同版本,所以android中的文件
- r - R中的数学约束优化
- php - PHP中window.location.origin的替代
- python - 如何循环遍历 BS4 数据并正确打印 div 标签
- java - 用 Kotlin 创建的房间数据库,用 Java 编写的活动,我可以这样做吗?