From 037d1a062a804e60d0c24acc47a9ff51ba49e105 Mon Sep 17 00:00:00 2001 From: Halil ibrahim Kalkan Date: Tue, 25 Dec 2018 16:17:01 +0300 Subject: [PATCH] Auto configure BsonClassMap for IHasExtraProperties --- .../Volo/Abp/MongoDB/AbpGlobalBsonClassMap.cs | 60 +++++++++++++++++++ .../Volo/Abp/MongoDB/MongoModelSource.cs | 2 + 2 files changed, 62 insertions(+) create mode 100644 framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/AbpGlobalBsonClassMap.cs diff --git a/framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/AbpGlobalBsonClassMap.cs b/framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/AbpGlobalBsonClassMap.cs new file mode 100644 index 0000000000..db74e1dae8 --- /dev/null +++ b/framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/AbpGlobalBsonClassMap.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using MongoDB.Bson.Serialization; +using Volo.Abp.Data; + +namespace Volo.Abp.MongoDB +{ + public static class AbpGlobalBsonClassMap + { + private static readonly HashSet PreConfiguredTypes = new HashSet(); + + /// + /// Configure default/base properties for the entity using . + /// This method runs single time for an for the application lifetime. + /// Subsequent calls has no effect for the same . + /// + public static void ConfigureDefaults() + { + ConfigureDefaults(typeof(TEntity)); + } + + /// + /// Configure default/base properties for the entity using . + /// This method runs single time for an for the application lifetime. + /// Subsequent calls has no effect for the same . + /// + public static void ConfigureDefaults(Type entityType) + { + lock (PreConfiguredTypes) + { + if (PreConfiguredTypes.Contains(entityType)) + { + return; + } + + ConfigureDefaultsInternal(entityType); + PreConfiguredTypes.Add(entityType); + } + } + + private static void ConfigureDefaultsInternal(Type entityType) + { + var map = new BsonClassMap(entityType); + + map.AutoMap(); + + if (entityType.IsAssignableTo()) + { + map.SetExtraElementsMember( + new BsonMemberMap( + map, + entityType.GetMember(nameof(IHasExtraProperties.ExtraProperties))[0] + ) + ); + } + + BsonClassMap.RegisterClassMap(map); + } + } +} diff --git a/framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/MongoModelSource.cs b/framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/MongoModelSource.cs index c5cb0da1c8..1ae6aeb124 100644 --- a/framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/MongoModelSource.cs +++ b/framework/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/MongoModelSource.cs @@ -58,6 +58,8 @@ namespace Volo.Abp.MongoDB { b.CollectionName = collectionAttribute?.CollectionName ?? collectionProperty.Name; }); + + AbpGlobalBsonClassMap.ConfigureDefaults(entityType); } protected virtual void BuildModelFromDbContextInstance(IMongoModelBuilder modelBuilder, AbpMongoDbContext dbContext)