如何在可空的枚举上测试空值

时间:2018-01-19 12:40:55

标签: linq azure-cosmosdb

我有属性_report_type的文档,它应该包含字符串“FTE”或“CAB”。 在遗留文档中,它可以为null或根本不存在(未定义),它们应该是“ContractorWorkReport”。

我的映射:

    public class Order : Document, IBaseEntity<string>
    {
        [JsonProperty(Order = 70, PropertyName = "orderData")]
        public OrderData Data { get; set; }      
    }

    public class OrderData
    {   

        [JsonProperty(Order = 60, PropertyName = "_order_type")]
        public OrderType? OrderType { get; set; }
    }

    [JsonConverter(typeof(StringEnumConverter))]
    public enum OrderType
    {
        [EnumMember(Value = "TFE")]
        ContractorWorkReport,
        [EnumMember(Value = "CAB")]
        BudgetElectricMeter
    }

我的查询基于:

var query = _client.CreateDocumentQuery<T>($"/dbs/{_databaseId}/colls/{CollectionId}");

    if (filter.OrderType.Value == OrderType.ContractorWorkReport)
        query = query.Where(o =>  o.Data.OrderType == null || !o.Data.OrderType.HasValue || o.Data.OrderType == filter.OrderType);
    else
        query = query.Where(o => o.Data.OrderType == filter.OrderType);

由于o.Data.OrderType == null,此查询崩溃,错误消息为: 无法将类型为“Microsoft.Azure.Documents.Sql.SqlNullLiteral”的对象强制转换为“Microsoft.Azure.Documents.Sql.SqlNumberLiteral”。'

如何解决这个问题?现在,我这样做,但它很脏......

if (filter.OrderType.Value == OrderType.ContractorWorkReport) 
            query = query.Where(o =>  o.Data.OrderType != OrderType.BudgetElectricMeter);
        else
            query = query.Where(o => o.Data.OrderType == filter.OrderType);

谢谢!

1 个答案:

答案 0 :(得分:1)

首先,我建议你将它用于CreateDocumentQuery中的第一个参数:UriFactory.CreateDocumentCollectionUri(databaseId, collectionId)

要回答您的问题,您要将int与null进行比较。作为枚举的o.Data.OrderType解析为int。您可能希望将其与默认枚举值0进行比较,或查询o.Data.OrderType根本不是关键字的文档

相关问题