具有可为空导航属性的 WCF 数据服务查询投影 [英] WCF Data Services query projection with nullable navigation properties

查看:28
本文介绍了具有可为空导航属性的 WCF 数据服务查询投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试针对 WCF 数据服务编写查询,该服务执行包含可为空导航属性的投影(即基础数据模型中的 FK 列可为空,因此关联为 0..1).项目语言是 VB.NET,不是我选择的.查询的示例部分:

I'm trying to write a query against a WCF data service that performs a projection that includes nullable navigation properties (i.e. the FK column in the underlying data model is nullable, so the association is 0..1). The project language is VB.NET, not by my choice. Example portion of query:

From t In DataServiceReference.Context.Transactions
Where t.ID = transactionID
Select
    CSM = t.WrittenByEmployee.Name, _
    t.CustomerFirstName

当针对 WrittenByEmployee 为 null 的行执行此查询时,我收到以下错误,正如人们所料:

When this query is executed against a row where WrittenByEmployee is null, I get the following error, as one would expect:

导航属性WrittenByEmployee"返回的条目为空且无法初始化.您应该在访问此属性之前检查空值.

An entry returned by the navigation property 'WrittenByEmployee' is null and cannot be initialized. You should check for a null value before accessing this property.

根据 this blog 可以在 C# 中使用三元 ?: 运算符进行条件空检查.然而,遗憾的是该项目是在 VB.NET 而不是 C# 中.我知道 VB 中的等价物是 If() 运算符,但它似乎无法按预期工作.如果我将上述查询更改为:

According to this blog conditional null checking is possible in C# by using the ternary ?: operator. However, sadly the project is in VB.NET and not C#. I know that the equivalent in VB is the If() operator, but it does not appear to work as desired. If I alter the above query to this:

Select
    CSM = If(t.WrittenByEmployee IsNot Nothing, t.WrittenByEmployee.Name, String.Empty)

我在运行时收到此错误:

I get this error at runtime:

不支持使用表达式 (t.WrittenBy Employee != null) 构造或初始化类型 (...) 的实例

Constructing or initializing instances of the type (...) with the expression (t.WrittenBy Employee != null) is not supported

我尝试反转测试但得到了类似的错误,只是使用 (t.WrittenByEmployee == null) 代替.

I tried inverting the test but got a similar error, only with (t.WrittenByEmployee == null) instead.

如何编写此查询,以数据服务接受的方式检查 WrittenByEmployee 导航属性是否存在空值?

How can I compose this query to check the WrittenByEmployee navigation property for nulls in a way that Data Services will accept?

推荐答案

感谢一位同事指出,当导航属性为 null 时,链接的博客返回的是 null 而不是常量!

Thanks to a co-worker who pointed out that the linked blog was returning null instead of a constant when the navigation property was null!

如果把上面的代码改成导航属性为null时返回null/Nothing,在C#和VB.NET中都有效!

If you change the above code to return null/Nothing when the navigation property is null, it works in C# and VB.NET!

Select
    CSM = If(t.WrittenByEmployee IsNot Nothing, t.WrittenByEmployee.Name, Nothing)
                                                                          ^^^^^^^

这篇关于具有可为空导航属性的 WCF 数据服务查询投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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