使用 C# SDK 忽略读取(反序列化)字段
Ignore field on read (deserialization) with C# SDK
我有一个包含两个字段的文档; name
和 documents
。
我希望在写入过程中将这两个字段序列化并插入到我的 collection 中。但是,我不希望 documents
在阅读过程中被反序列化(我很高兴这个字段为空),
这是实体 class:
public class EmployeeDocument
{
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("documents")]
public List<string> Documents { get; set; }
}
我怎样才能做到这一点?
我认为不可能忽略反序列化的属性,但不能忽略序列化。
我认为这不是最好的方法。
如果你不想从文档中读取所有属性,你可以在投影中排除它们,如果你想拥有相同的 EmployeeDocument
class,你可以将你的 BsonDocument
反序列化到它,我的意思是:
var emps = db.GetCollection<EmployeeDocument>("empl");
var employees =emps.Find(x=>true)
.Project(Builders<EmployeeDocument>.Projection.Exclude(x=>x.Documents))
.ToList()
.Select(x=>BsonSerializer.Deserialize<EmployeeDocument>(x));
我有一个包含两个字段的文档; name
和 documents
。
我希望在写入过程中将这两个字段序列化并插入到我的 collection 中。但是,我不希望 documents
在阅读过程中被反序列化(我很高兴这个字段为空),
这是实体 class:
public class EmployeeDocument
{
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("documents")]
public List<string> Documents { get; set; }
}
我怎样才能做到这一点?
我认为不可能忽略反序列化的属性,但不能忽略序列化。
我认为这不是最好的方法。
如果你不想从文档中读取所有属性,你可以在投影中排除它们,如果你想拥有相同的 EmployeeDocument
class,你可以将你的 BsonDocument
反序列化到它,我的意思是:
var emps = db.GetCollection<EmployeeDocument>("empl");
var employees =emps.Find(x=>true)
.Project(Builders<EmployeeDocument>.Projection.Exclude(x=>x.Documents))
.ToList()
.Select(x=>BsonSerializer.Deserialize<EmployeeDocument>(x));