简体   繁体   中英

MongoDB c# driver _id field and SetIdMember()

I have set the SetIdMember() for a class map to point to an element within the object:

BsonClassMap.RegisterClassMap<Person>(x =>
    {
        x.AutoMap();
        x.SetIdMember(x.GetMemberMap(p => p.PersistedId));
    });

Which works fine, however I was looking in the mongo data (via MongoVUE) and noticed that the PersistedId field is not stored anywhere in the database, I presume this is because it maps it to the _id field.

Now for 99% of scenarios im sure that is fine, however in this case I am using a non-strongly typed model, and pulling back a raw BsonDocument, then turning it to JSON for handing to a clientside script to then use further. However it is expecting to get a PersistedId field in the JSON but it doesn't exist, it is just _id.

So is there a way for me to get it to do its whole unique _id field thing, but also get it to write out the PersistedId field to the database too? (I know its going to be duplicated data, but its not a major worry)

You can add a readonly property and let the driver know to store it in the database as PersistedId.

public class Entity
{
    public ObjectId Id { get; set; }

    public ObjectId PersistedId 
    {
        get { return Id; }
    }
}

BsonClassMap.RegisterClassMap<Person>(x =>
{
    x.AutoMap();
    x.MapMember(x => x.PersistedId);
});

However, I'm not sure this is the best idea. You likely shouldn't be sharing your database models with your UI in a server environment like this. Rather, you should be mapping from your database models to UI models. This provides a large number of benefits, such as aggregating models, transforming models, etc... so that your UI isn's so coupled to your UI. But, ultimately, it is your call.

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