Linq 如何在可空枚举上测试空值
我有属性为“报告”类型的文档,它应该包含字符串“FTE”或“CAB”。 在旧文档中,它可以为null或根本不存在(未定义),它们应该是“ContractorWorkReport” 我的映射:Linq 如何在可空枚举上测试空值,linq,azure-cosmosdb,Linq,Azure Cosmosdb,我有属性为“报告”类型的文档,它应该包含字符串“FTE”或“CAB”。 在旧文档中,它可以为null或根本不存在(未定义),它们应该是“ContractorWorkReport” 我的映射: public class Order : Document, IBaseEntity<string> { [JsonProperty(Order = 70, PropertyName = "orderData")] public OrderData
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
}
谢谢 首先,我建议您将其用于CreateDocumentQuery中的第一个参数:
UriFactory.CreateDocumentCollectionUri(databaseId,collectionId)
要回答您的问题,您需要将int与null进行比较
o.Data.OrderType
,作为一个枚举,解析为一个int。您可能希望将其与默认枚举值0
进行比较,或者查询o.Data.OrderType
根本不是键的文档。谢谢您的回答:UriFactory.CreateDocumentCollectionUri(databaseId,collectionId)确实更好。对于默认的枚举值,这里的枚举可以为null,因此我希望它理解null是什么。我可以测试,但很确定它不会工作,因为它可以为null或未定义。对于“或查询o.Data.OrderType根本不是键的文档”,不确定您的意思是什么?谢谢@就cosmosDB而言,枚举不可为空。读一下例外情况。您正在尝试将null
转换为int。显然,cosmosDB(或其客户端)正在将您的枚举解释为int。这是不可为null的。如果您想使用NullThank,我建议您将枚举强制转换为字符串。但是,如何将枚举强制转换为字符串呢?我尝试了.ToString()和其他方法,但提供者从未理解如何正确地“查询”它
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);
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);