英文:
MongoDB C# Property serializing string and int for query
问题
我想查询一些“A”集合。类“A”具有一个名为Status的属性,其定义如下:
public class Status<T>
[BsonRepresentation(BsonType.String)] // <- 这是后来添加的!
public T Code { get; set; }
public DateTime Timestamp { get; set; }
public int UserId { get; set; }
}
所以A看起来像这样:
public class A {
public Status<MyEnum> Status {get; set;}
}
其中T通常是一个枚举。我尝试像这样查询它:
var f = Builders<A>.Filter.Or(
Builders<A>.Filter.Eq("Status.Code", intStatus),
Builders<A>.Filter.Eq("Status.Code", stringStatus)
);
filterCondition &= f;
现在的问题是数据库中有旧记录,其中Status.Code仍然是int。现在查询只能找到已经存储为string的记录。
我不太了解问题,但我怀疑驱动程序在序列化时存在困难,因此忽略了int。是否有一种配置方式可以使查询同时找到两者?
英文:
I'd like to query some collection of "A". Class "A" has a Status property which is defined like this:
public class Status<T>
[BsonRepresentation(BsonType.String)] //<- this was added some time later!
public T Code { get; set; }
public DateTime Timestamp { get; set; }
public int UserId { get; set; }
}
so A looks like:
public class A {
public Status<MyEnum> Status {get; set;}
}
where T usually is an enum. I try to query it like this:
var f = Builders<A>.Filter.Or(
Builders<A>.Filter.Eq("Status.Code", intStatus),
Builders<A>.Filter.Eq("Status.Code", stringStatus)
);
filterCondition &= f;
Now the problem is there are older records in the DB where Status.Code is still an int. Now the query only every finds the records where Status.Code is already stored as a string.
I dont understand the problem good enough but I suspect the driver has a hard time serializing it and thus ignores ints. Is there a way to config this, so that the query finds both?
答案1
得分: 1
是的,当您应用[BsonRepresentation(BsonType.String)]
属性时,序列化器将将Code
字段的值转换为string
类型。
这种方法可能看起来有点不太美观,但使用BsonDocument
可以将要序列化的值转义为string
。
var f = Builders<A>.Filter.Or(
new BsonDocument("Status.Code", intStatus),
Builders<A>.Filter.Eq("Status.Code", stringStatus)
);
另一种方法是将intStatus
值传递为BsonValue
类型。
var f = Builders<A>.Filter.Or(
Builders<A>.Filter.Eq("Status.Code", BsonValue.Create(intStatus)),
Builders<A>.Filter.Eq("Status.Code", stringStatus)
);
英文:
Yes, as you apply the [BsonRepresentation(BsonType.String)]
attribute, the serializer will convert the Code
field value as string
type.
This approach may look ugly, but using BsonDocument
would be able to escape the value to be serialized as string
.
var f = Builders<A>.Filter.Or(
new BsonDocument("Status.Code", intStatus),
Builders<A>.Filter.Eq("Status.Code", stringStatus)
);
Another approach is that pass the intStatus
value as the BsonValue
type.
var f = Builders<A>.Filter.Or(
Builders<A>.Filter.Eq("Status.Code", BsonValue.Create(intStatus)),
Builders<A>.Filter.Eq("Status.Code", stringStatus)
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论