mongodb 仅当用bson序列化时才忽略属性

toiithl6  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(94)

我需要配置序列化程序,以便在序列化期间属性不会落入Bson Document,但在非序列化期间会落入Bson Document。当使用Bson Ignore属性时,序列化和非序列化不起作用(这是逻辑上的),但我需要一个稍微不同的逻辑

3lxsmp7m

3lxsmp7m1#

我得出了以下解决方案:我决定对所需的属性使用BsonIgnoreIfNullAttribute,创建了自己的SourceIsIgnoredAttribute属性,并在自动Map器的扩展中处理它。

public static class UnmapIgnoredMembersExtension
{
    /// <summary>
    /// Unmaps the ignored members with attribute - <see cref="SourceIsIgnoredAttribute"/>.
    /// </summary>
    /// <typeparam name="TSource">The type of the source.</typeparam>
    /// <typeparam name="TDestination">The type of the destination.</typeparam>
    /// <param name="mappingExpression">The mapping expression.</param>
    /// <returns></returns>
    public static IMappingExpression<TSource, TDestination> UnmapIgnoredMembers<TSource, TDestination>(this IMappingExpression<TSource, TDestination> mappingExpression)
    {
        var targetProperties = typeof(TDestination).GetProperties(
            BindingFlags.Public
            | BindingFlags.Instance
            | BindingFlags.NonPublic
            ).Where(property => Attribute.IsDefined(property, typeof(SourceIsIgnoredAttribute)))
            .ToList();

        foreach (var property in targetProperties)
        {
            mappingExpression
                .ForMember(property.Name, q => q.Ignore());
        }

        return mappingExpression;
    }
}

因此,不必要的数据不会进入数据库,我可以使用查找和其他功能,我需要没有任何问题。

相关问题