在Linq中LEFT JOIN时出现非Nullable值类型问题

时间:2012-09-12 22:50:53

标签: c# linq

我打算在一个需要使用 Linq 的WinForms项目上工作,但我一无所知,所以我才开始学习。

在阅读有关Linq的教程后,我使用Microsoft Windows SDK附带的System.Data.Linq.DataContext工具创建了SqlMetal。我使用的数据库是“Northwind”

我能够进行如下简单查询:

Northwind db = new Northwind("Data Source=local;Initial Catalog=Northwind;Integrated Security=True");

var query = from c in db.Customers
            join o in db.Orders on c.CustomerID equals o.CustomerID 
            select new
            {
                Customer_ID = c.CustomerID,
                Customer_Name = c.ContactName,
                Order_ID = o.OrderID
            };

然后我用DataGridView显示结果,并且顺利进行。

但是现在我正面临着一个我无法解决的问题。

我尝试修改上一个查询以生成LEFT OUTER JOIN,所以我做的是以下内容:

    var query = from c in db.Customers
            join o in db.Orders on c.CustomerID equals o.CustomerID into j
            from or in j.DefaultIfEmpty()
            select new
            {
                Customer_ID = c.CustomerID,
                Customer_Name = c.ContactName,
                Order_ID = or.OrderID
            };

但是,当我尝试在DataGridView中显示这些数据集时,会出现错误:

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

我知道此问题是由没有“订单”的“客户”引起的,因此系统会尝试将null值设为int变量。

但是,如何在没有此错误的情况下制作LEFT OUTER JOIN

提前谢谢。

2 个答案:

答案 0 :(得分:3)

您不应将类型转换为字符串。简单地将它转换为等效的可空类型:

var query = from c in db.Customers
            join o in db.Orders on c.CustomerID equals o.CustomerID into j1
            from or in j1.DefaultIfEmpty()
            select new
            {
                Customer_ID = c.CustomerID,
                Customer_Name = c.ContactName,
                Order_ID = (int?)or.OrderID
            };

答案 1 :(得分:0)

我想我刚刚找到答案:

var query = from c in db.Customers
            join o in db.Orders on c.CustomerID equals o.CustomerID into j1
            from or in j1.DefaultIfEmpty()
            select new
            {
                Customer_ID = c.CustomerID,
                Customer_Name = c.ContactName,
                Order_ID = or.OrderID == null ? "[null]" : or.OrderID.ToString()
            };

但我很感激,如果有人有更好的答案