简体   繁体   中英

Ignore a [BsonIgnore] when using BsonSerializer.Deserialize()

I have a 'User' class with a list of organisations. With [BsonIgnore] I'm not saving the organisations. They are in another collection. That's why 'User' also has a list of organisationId's. This works fine.

public class User
{
    public ObjectId _id { get; set; }
    public List<ObjectId> OrganisationIds { get; set; }
    [BsonIgnore]
    public List<Organisation> Organisations { set; get; }
}

Problem

The problem is when I do a query to get the User and his organisations. On deserializing the BsonDocument, It throws an exception. Something like: 'Organisations' on 'User' does not exists.

var aggregation = _userService.GetCollection()
    .Aggregate<User>()
    .Lookup<User>("Organisations", "OrganisationId", "_id", "Organisation");

var firstUser = aggregation.FirstOrDefault();

var user = BsonSerializer.Deserialize<User>(firstUser);

I don't want to save organisations in a user. How should I approach this?

The [BsonIgnore] caused the trouble. It didn't complain about there is no such field, but it complained when aggregating.

I have the following, and it's working>

public class User
{
    public ObjectId _id { get; set; }
    public List<ObjectId> OrganisationIds { get; set; }
}

public class UserAggregate
{
    public List<ObjectId> OrganisationIds { get; set; }
    public ObjectId _id { get; set; }
    public List<Organisation> Organisations { set; get; }
}

public class Organisation
{
    public ObjectId _id { get; set; }
    public string Name { get; set; }
}

string connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);

var db = client.GetDatabase("test");
    var instances = db.GetCollection<User>("Users");
var instances2 = db.GetCollection<Organisation>("Organisations");
var aggregation = instances.Aggregate().Match(...).Lookup(foreignCollection: instances2,
        localField: x => x.OrganisationIds, foreignField: x => x._id,
        @as: (UserAggregate pr) => pr.Organisations)
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM