内部?与 Linq 问题中的 LEFT OUTER JOIN 时的 int 比较 [英] int? and int comparison when LEFT OUTER JOIN in Linq issue

查看:20
本文介绍了内部?与 Linq 问题中的 LEFT OUTER JOIN 时的 int 比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要使用 Linq-To-Sql 的 WinForms 项目.我已经能够使用 SqlMetal 工具创建我的 DataContext,并进行一些查询.但是现在我有一个我无法解决的问题.

我正在尝试制作一个 LEFT OUTER JOIN 如下:

MyDatabase db = new MyDatabase(...);var query = from p in db.ParentTable在新的 {A = p.child_ID, B = p.OtherID} 上加入 db.ChildTable等于新的 {A = t.ID, B = t.OtherID} 到 j1来自 j1.DefaultIfEmpty() 中的 c选择新的{...};

当我编写此查询时,会在编译时在 join 字中引发错误:

<块引用>

join 子句中的表达式之一的类型不正确.调用GroupJoin"时类型推断失败

我知道这个错误是由 p.child_IDt.ID 之间的比较引起的,因为 p.child_IDint?t.IDint.但是,我该如何解决这个问题?如何在不出现此错误的情况下执行 LEFT OUTER JOIN?

p.child_IDint? 因为此列在 SQL 中被标记为 IS NULL.

希望有人能帮助我,提前致谢.

解决方案

您可以使用 GetValueOrDefault() 方法.它检索当前 Nullable 对象的值,或对象的默认值.

就你的例子而言:

var query = from p in db.ParentTable在新的 {A = p.child_ID.GetValueOrDefault(0), B = p.OtherID} 上加入 db.ChildTable等于新的 {A = t.ID, B = t.OtherID} 到 j1来自 j1.DefaultIfEmpty() 中的 c选择新的{...};

如果 p.child_ID 变为 null 则返回 0.希望这会有所帮助!!

I am working on a WinForms project which requires to use Linq-To-Sql. I have been able to create my DataContext using the SqlMetal tool, and make some queries. But right now I have a problem that I havent been able to solve.

I am trying to make a LEFT OUTER JOIN as following:

MyDatabase db = new MyDatabase(...);

 var query = from p in db.ParentTable
             join t in db.ChildTable on new {A = p.child_ID, B = p.OtherID}
             equals new {A = t.ID, B = t.OtherID} into j1
             from c in j1.DefaultIfEmpty()
             select new
             {
                  ...
             };

When I write this query an error is raised at compile-time in the join word:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'

I know this error is caused by the comparison between p.child_ID and t.ID since p.child_ID is int? and t.ID is int. But, How can I solve this? How can I perform the LEFT OUTER JOIN without having this error??

p.child_ID is int? since this column is marked as IS NULL in SQL.

Hope someone can help me, thanks in advance.

解决方案

You can use GetValueOrDefault() method. It retrieves the value of the current Nullable object, or the object's default value.

In terms of your example :

var query = from p in db.ParentTable
            join t in db.ChildTable on new {A = p.child_ID.GetValueOrDefault(0), B = p.OtherID}
            equals new {A = t.ID, B = t.OtherID} into j1
            from c in j1.DefaultIfEmpty()
            select new
            {
                ...
            };

If the p.child_ID become null than it will return 0. Hope this will help !!

这篇关于内部?与 Linq 问题中的 LEFT OUTER JOIN 时的 int 比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆