Do not insert field if null or empty

后端 未结 2 1056
暗喜
暗喜 2021-01-04 23:51

I have a C# class with some fields and some of them are null. Those that are null I do not want to be inserted into db with null value. I do not want them inserted into db a

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 00:07

    Ensure you are registering the new convention pack early enough. If any classes have already been mapped before you register the new convention pack they won't be updated.

    Here's my test code:

    public class C
    {
        public int Id { get; set; }
        public string S { get; set; }
    }
    
    public static class Program
    {
        public static void Main(string[] args)
        {
            ConventionRegistry.Register(
                "Ignore null values",
                new ConventionPack
                {
                    new IgnoreIfNullConvention(true)
                },
                t => true);
    
            var client = new MongoClient("mongodb://localhost");
            var server = client.GetServer();
            var database = server.GetDatabase("test");
            var collection = database.GetCollection("test");
    
            collection.Drop();
            collection.Insert(new C { Id = 1, S = null });
    
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
    }
    

    The following document was inserted into the database:

    db.test.find()

    { "_id" : 1 }
    

    Source: https://groups.google.com/forum/#!topic/mongodb-user/7-NFXBNeEXs

提交回复
热议问题