Dave New
Dave New

Reputation: 40062

Ignore field on read (deserialization) with C# SDK

I have a document with two fields; name and documents.

I want both fields to be serialized and inserted into my collection during writing. BUT, I do not want documents to be deserialized during reading (I am happy with this field being null),

Here is the entity class:

public class EmployeeDocument
{
    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("documents")]
    public List<string> Documents { get; set; }
}

How could I achieve this?

Upvotes: 1

Views: 1100

Answers (1)

Maksim Simkin
Maksim Simkin

Reputation: 9679

I think it's not possible to ignore a property for deserialization, but not for serialization. And i think it's not the best approach. If you want to read not all properties from the document, you could exclude them on projection, if you than want to have the same EmployeeDocument class, you could deserialize your BsonDocument to it, i mean something like:

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));

Upvotes: 2

Related Questions