Creating MongoDB Unique Key with C#

后端 未结 6 1667
故里飘歌
故里飘歌 2020-12-29 03:08

I am fighting to create a unique field EmailAddress. I\'ve already seen in forums that I have to create an index, but it didn\'t work out for me so far. Does an

6条回答
  •  庸人自扰
    2020-12-29 04:05

    In my opinion a better and more feasible way to do this is by creating a custom attribute, then with c# you could get the properties decorated with that attribute and add a unique index, this approach would be generic and very simple to use. Example below:

    My custom attribute: MongoUniqueStringIndex

     public class DynamicFieldConfig
    {
        public string InputType { get; set; }
        [MongoUniqueStringIndex]
        public string Name { get; set; }
        public string Label { get; set; }
        public List Options { get; set; } = new List();
        public string LookupTypeName { get; set; }
        public int Type { get; set; } //int to enum
        public string Value { get; set; }
        public List Validations { get; set; } = new List();
    }
    

    then where you get the collection, for example in my Data Access class I do this:

            public MongoDataAccess(IDatabaseSettings settings)
        {
            // todo: create a connection service/factory to get connection
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);
            
            var entityName = new Pluralizer().Pluralize(typeof(TMongoEntity).Name);
            _entityStore = database.GetCollection(entityName);
    
            var uniqueStringIndexProperties = typeof(TMongoEntity).GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(MongoUniqueStringIndex))).ToList();
            if (uniqueStringIndexProperties.Any())
                foreach (var propertyInfo in uniqueStringIndexProperties)
                {
                    var options = new CreateIndexOptions { Unique = true };
                    var propertyInfoName = propertyInfo.Name;
                    var field = new StringFieldDefinition(propertyInfoName);
                    var indexDefinition = new IndexKeysDefinitionBuilder().Ascending(field);
                    var indexModel = new CreateIndexModel(indexDefinition, options);
                    _entityStore.Indexes.CreateOne(indexModel);
                }
        }
    

提交回复
热议问题