gpt4 book ai didi

c# - 使用 MongoDB 时如何按约定应用 BsonRepresentation 属性

转载 作者:可可西里 更新时间:2023-11-01 09:11:59 24 4
gpt4 key购买 nike

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

我尝试添加 StringObjectIdIdGeneratorConvention 但这似乎无法解决问题。

有什么想法吗?

最佳答案

是的,我也注意到了这一点。由于某些原因,StringObjectIdIdGeneratorConvention 的当前实现似乎不起作用。这是一个有效的方法:

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

关于c# - 使用 MongoDB 时如何按约定应用 BsonRepresentation 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com