【问题标题】:C# EF6 issue binding Linq result to DataGridView where date column is nullC# EF6 问题将 Linq 结果绑定到日期列为空的 DataGridView
【发布时间】:2015-02-21 16:16:22
【问题描述】:

所有,我在下面的 Linq 查询中遇到问题:

private void BindDataGrid(string _filter)
{
    using (var context = new Kennels_Data_ModelContainer())
    {
        var grid = context.Pricings
            .Where(x => x.AnimalType.Type == _filter)
            .Select(x=> new {x.PriceStart, x.PriceEnd, x.Price});

        if (grid != null)
        {
            var results = grid.ToList();
            pricingDataGridView.DataSource = results;
            pricingDataGridView.Columns[0].Width = 80;
            pricingDataGridView.Columns[1].Width = 80;
            pricingDataGridView.Columns[2].Width = 57;
        }
    }
}

我正在使用 Visual Studio 2013 和实体框架 6,以及 SQL Server 2012。

在我更改数据库中的 PriceEnd 列以允许它保存空值之前,该查询运行良好,并且我知道其中至少有一行包含空值。

此代码保存在 Windows 窗体中,并由窗体的 Load 方法调用,以绑定到 pricingdataGridView

代码抛出System.NullReferenceException,附加信息为Object reference not set to an instance of an object

我已经查看了所有内容,我可以在 Linq 查询的 where 子句中找到大量关于处理 null 的引用,但我没有发现任何与处理返回集中的 null 值相关的内容。

感谢任何帮助。

干杯。

【问题讨论】:

    标签: c# linq-to-entities entity-framework-6


    【解决方案1】:

    首先,EF模型有更新吗?如果在您的模型中PriceEnd 字段保持为decimal,则可能会抛出 NullReferenceException,但应该变为decimal?

    LINQ null 检查,避免这些记录:

    ... context.Pricings.Where(x => x.AnimalType.Type == _filter && x.PriceEnd != null)...
    

    【讨论】:

    • 感谢您的回复,但即使 PriceEnd 列包含空值,我也需要返回记录。问题在于将记录(即使该字段为空)绑定到 DataGridView。
    • @BarryO'Kane DataGridViewCellStyle.NullValue Property 也许?我没有相关的 WinForms 经验。
    • 抱歉延迟响应,我会接受您的回答是正确的,因为它有助于正确格式化网格中的空值。但事实证明,我已将用于将数据绑定到 datagridview 的代码移到构造函数中 InitializeComponent() 之前。这解决了问题。
    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多