本文介绍了使用MongoDB时如何按约定应用BsonRepresentation属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将[BsonRepresentation(BsonType.ObjectId)]应用于所有表示为字符串的id,而不得不用该属性装饰我的所有id.

I'm trying to apply [BsonRepresentation(BsonType.ObjectId)] to all ids represented as strings withoput having to decorate all my ids with the attribute.

我尝试添加StringObjectIdIdGeneratorConvention,但似乎无法对其进行排序.

I tried adding the StringObjectIdIdGeneratorConvention but that doesn't seem to sort it.

有什么想法吗?

推荐答案

是的,我也注意到了. StringObjectIdIdGeneratorConvention的当前实现似乎由于某些原因而无法正常工作.这是一个可行的方法:

Yeah, I noticed that, too. The current implementation of the StringObjectIdIdGeneratorConvention does not seem to work for some reason. Here's one that works:

public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class StringObjectIdIdGeneratorConventionThatWorks : ConventionBase, IPostProcessingConvention
{
    /// <summary>
    /// Applies a post processing modification to the class map.
    /// </summary>
    /// <param name="classMap">The class map.</param>
    public void PostProcess(BsonClassMap classMap)
    {
        var idMemberMap = classMap.IdMemberMap;
        if (idMemberMap == null || idMemberMap.IdGenerator != null)
            return;
        if (idMemberMap.MemberType == typeof(string))
        {
            idMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId));
        }
    }
}

public class Program
{
    static void Main(string[] args)
    {
        ConventionPack cp = new ConventionPack();
        cp.Add(new StringObjectIdIdGeneratorConventionThatWorks());
        ConventionRegistry.Register("TreatAllStringIdsProperly", cp, _ => true);

        var collection = new MongoClient().GetDatabase("test").GetCollection<Person>("persons");

        Person person = new Person();
        person.Name = "Name";

        collection.InsertOne(person);

        Console.ReadLine();
    }
}

这篇关于使用MongoDB时如何按约定应用BsonRepresentation属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 19:27