diff options
Diffstat (limited to 'Software/Visual_Studio_v2/Tango.DAL.Mongo/MongoRepository.cs')
| -rw-r--r-- | Software/Visual_Studio_v2/Tango.DAL.Mongo/MongoRepository.cs | 24 |
1 files changed, 23 insertions, 1 deletions
diff --git a/Software/Visual_Studio_v2/Tango.DAL.Mongo/MongoRepository.cs b/Software/Visual_Studio_v2/Tango.DAL.Mongo/MongoRepository.cs index d268f434d..864bb17cc 100644 --- a/Software/Visual_Studio_v2/Tango.DAL.Mongo/MongoRepository.cs +++ b/Software/Visual_Studio_v2/Tango.DAL.Mongo/MongoRepository.cs @@ -6,6 +6,8 @@ using System.Reflection; using Tango.DAL.Attributes; using System.Linq.Expressions; using MongoDB.Driver.Linq; +using System.Linq; +using Newtonsoft.Json; namespace Tango.DAL.Mongo { @@ -25,7 +27,27 @@ namespace Tango.DAL.Mongo { if (_collection == null) { - _collection = _database.GetCollection<T>(typeof(T).GetCustomAttribute<MongoCollectionAttribute>().Name); + _collection = _database.GetCollection<T>(typeof(T).GetCustomAttribute<CollectionAttribute>().Name); + + foreach (var prop in typeof(T).GetProperties()) + { + if (prop.GetCustomAttribute<UniqueAttribute>() != null) + { + var indices = _collection.Indexes.List().ToList().Select(x => JsonConvert.DeserializeObject<MongoIndex>(x.ToString())).ToList(); + + if (!indices.Exists(x => x.name == prop.Name)) + { + var builder = Builders<T>.IndexKeys; + var indexModel = new CreateIndexModel<T>(builder.Ascending(prop.Name), new CreateIndexOptions() + { + Unique = true, + Name = prop.Name, + }); + + _collection.Indexes.CreateOne(indexModel); + } + } + } } return _collection; |
