Creating MongoDB Unique Key with C#

后端 未结 6 1650
故里飘歌
故里飘歌 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 03:45

    here's a working program using MongoDB.Entities (disclaimer: I'm the author)

    using System;
    using MongoDB.Driver;
    using MongoDB.Entities;
    
    namespace StackOverflow
    {
        public class User : Entity
        {
            public string Name { get; set; }
            public string EmailAddress { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                new DB("test");
    
                DB.Index()
                  .Options(o => o.Unique = true, o => o.Background = false)
                  .Key(u => u.EmailAddress, Type.Ascending)
                  .Create();
    
                var user1 = new User { Name = "First User", EmailAddress = "email@domain.com" };
                user1.Save();
    
                try
                {
                    var user2 = new User { Name = "Second User", EmailAddress = "email@domain.com" };
                    user2.Save();
                }
                catch (MongoWriteException x)
                {
                    Console.WriteLine(x.Message);
                    Console.ReadKey();
                }
            }
        }
    }
    

    trying to create a second user with the same email address results in the following exception:

    A write operation resulted in an error. E11000 duplicate key error collection: test.User index: EmailAddress(Asc) dup key: { : "email@domain.com" }

提交回复
热议问题