为所有类实现 BsonIgnoreExtraElements

问题描述 投票:0回答:2

我正在使用 mongDb 和 MongoDrive,我想知道如何在我的所有类中实现

[BsonIgnoreExtraElements]

我知道有办法通过

ConventionProfile
,但我不知道如何实现。

c# mongodb
2个回答
39
投票

编辑

根据 Evereq 的评论,以下内容已过时。 现在使用:

var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true);

使用

SetIgnoreExtraElementsConvention
方法(来自 C# 驱动程序序列化教程约定部分):

var myConventions = new ConventionProfile();
myConventions.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention()));
BsonClassMap.RegisterConventions(myConventions, (type) => true);

参数

(type) => true
是一个取决于类类型的谓词,它决定是否应用约定。 因此,根据您的要求,它应该简单地返回 true 无论如何;但如果您愿意,您可以使用它来设置/排除给定类型的约定。


0
投票

最好的方法之一是为所有实体继承基类,并在基类顶部添加一个装饰器

在BaseEntity.cs中

[BsonIgnoreExtraElements(Inherited = true)]
public class BaseEntity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    [JsonPropertyName("_id")]
    public string Id { get; set; }
    
    [BsonElement("createdAt")]
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
    
    [BsonElement("updatedAt")]
    public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
    
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonElement("createdBy")]
    public string CreatedBy { get; set; }
    
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonElement("updatedBy")]
    public string UpdatedBy { get; set; }
}

在 UserEntity.cs 中

public class UserEntity : BaseEntity
{
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonElement("businessId")]
    [BsonRequired]
}

注: [BsonIgnoreExtraElements(继承= true)] 在此 Inherited = true 很重要,否则它将无法按预期工作

© www.soinside.com 2019 - 2024. All rights reserved.