简体   繁体   中英

How to get BsonElement value in dotnet core to get the string of mongodb field name

hi every body i am stil new in mongo but i hop to get help of your great experiances, in my project i am using BsonElement to name all field for example:

        [BsonElement("isremoved")]
        public bool IsRemoved { get; set; }

i have query in method as:

        public async Task<Player> Delete(string PlayerId)
        {
            var filter = Builders<Player>.Filter.And(Builders<Player>.Filter.Eq(x => x.PlayerId, PlayerId));
            var item = Builders<Player>.Update.Combine(Builders<Player>.Update.Set("isremoved", true));
            return await _dbCollection.FindOneAndUpdateAsync(filter, item);
        }

i think this not best way to build this query, and we actually intend to change fields name in production to be short name as 'isr' in replace of 'isremoved', in this case how to get the BsonElement element value from class property itself (IsRemoved)

You can retrieve a custom attribute value like this:

typeof(Player).GetProperty(nameof(Player.IsRemoved)).GetCustomAttribute<BsonElementAttribute>().ElementName

Don't forget to import using MongoDB.Bson.Serialization.Attributes; and using System.Reflection; .

You can pass in an expression like you've done for the Equals filter:

var update = Builders<Player>.Update.Set(player => player.IsRemoved, true);

return await _dbCollection.FindOneAndUpdateAsync(filter, update);

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