Created
May 3, 2012 12:29
-
-
Save Yegoroff/2585324 to your computer and use it in GitHub Desktop.
MongoDb PreserveValueIfNull
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class MongoSerializationExtensions | |
{ | |
public static BsonMemberMap PreserveValueIfNull(this BsonMemberMap memberMap) | |
{ | |
var originalSetter = memberMap.Setter; | |
Action<object, object> preserveSetter = (obj, value) => { | |
if (value != null) | |
originalSetter(obj, value); | |
}; | |
var field = typeof(BsonMemberMap).GetField("_setter", BindingFlags.NonPublic | BindingFlags.Instance); | |
if (field == null) | |
throw new InvalidOperationException("BsonMemberMap format has changed, please correct this dirty hack."); | |
field.SetValue(memberMap, preserveSetter); | |
return memberMap; | |
} | |
} | |
// Usage | |
... | |
public static void Install() | |
{ | |
var database = MongoDatabase.Create("server=localhost; database=test"); | |
if (!database.CollectionExists("test")) | |
database.CreateCollection("test"); | |
BsonClassMap.RegisterClassMap<Test>( cm => { | |
cm.AutoMap(); | |
cm.MapField(t => t.Collection).PreserveValueIfNull(); | |
}); | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment