serializationravendb

How to ignore a property during serialization for RavenDB


Using RavenDB 6, how do I prevent the serialization of a specific property to the database. I've tried [JsonIgnore], but it doesn't work.


Solution

  • Using [JsonIgnore] should work for you.
    For example, this simple test passes with RavenDB v6.0

            public class User
            {
                public string Name { get; set; }
    
                [JsonIgnore] // Newtonsoft.Json.JsonIgnore
                public string PropToIgnore { get; set; }
            }
            
            [Fact]
            public void Test()
            {
                var store = new DocumentStore
                {
                     Urls = new[] { "http://localhost:8080"},
                     Database = "myDb"
                };
                store.Initialize();
                
                using (store)
                {
                    using (var session = store.OpenSession())
                    {
                        var user = new User()
                        { 
                            Name = "myName",
                            PropToIgnore = "someText"
                        };
    
                        session.Store(user, "Users/1");
                        session.SaveChanges();
                    }
                    
                    using (var session = store.OpenSession())
                    {
                        User testUser = session.Load<User>("Users/1");
                        Assert.True(testUser.PropToIgnore == null);
                        // The PropToIgnore property was not stored on disk
                        // and comes back as null.
                    }
                }
            }