问题描述
我有带有3个字符串字段(国家,省,城市)的对象.它们可以包含null或某些字符串名称.
I have objects with 3 string fields Country, Province, City. They can contain null or some string name.
我想用完全相同的值查询所有数据.
I wanna query all data with the exact same values.
例如,我需要所有数据,其中
For Example i need all data where
City = null,
Province = "WA",
Country = "USA"
我创建了BsonDocument:
I created BsonDocument:
var lookup = new QueryDocument
{
{"GeoPosition.City", userLocation.City},
{"GeoPosition.Province", userLocation.Province},
{"GeoPosition.Country", userLocation.Country}
};
但是空字段被扔掉了,文档看起来像这样:
But null field was thrown away and document looks like:
{
"GeoPosition.Province" : "WA",
"GeoPosition.Country" : "USA"
}
如果我想使用
Query.EQ("GeoPosition.City", userLocation.City)
我有一个例外,说参数不能为空.
I have exception saying that parametr cant be null.
正如我在文档中所看到的,如果值等于null,则构建查询检查不会有任何问题.因此,这是C#驱动程序的问题.有什么想法可以解决这个问题吗?
As i see in documentation there is no problem in building query cheking if value equals null. So that is a problem with C# driver. Any ideas how to solve this problem?
推荐答案
取决于城市变量的数据类型.如果city变量的类型为BsonValue,则可以使用??.直接操作:
Depends on the data type of your city variable. If the city variable is of type BsonValue you can use the ?? operator directly:
BsonValue city = null;
var query = Query.EQ("city", city ?? BsonNull.Value);
Console.WriteLine(query.ToJson());
如果您的city变量为字符串类型,则需要进行额外的转换以使编译器满意:
If your city variable is of type string you need an extra conversion cast to make the compiler happy:
string city = null;
var query = Query.EQ("city", (BsonValue)city ?? BsonNull.Value);
Console.WriteLine(query.ToJson());
这篇关于如何使用C#官方驱动程序创建具有Null值的Bson文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!