Reputation: 489
Here is the information about my development environment:
-MongoDB 3.0.0
-MongoDB C# Driver Version 1.7.0.4714
-Microsoft Visual Studio Professional 2013
-.NET Framework 4.0
Let's say that I have the following C# POCO Location class
public class Location
{
public Object Id { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public String LocDescription { get; set; }
}
The aforementioned class is a C# POCO that will map to a MongoDB collection called Location.
When the application starts up, the following code will get executed from Global.asax.cs
if (false == BsonClassMap.IsClassMapRegistered(typeof(Location)))
{
BsonClassMap.RegisterClassMap<Location>(cm =>
{
cm.AutoMap();
});
} //
We need the saving to data to be intelligent enough to do the following:
{
"_id" : ObjectId("567f90bc0a73fc5b0a81f231"),
"lat" : 309,
"lng" : 45,
"LocDescription" : "passed the bridge, take a left at Rover Street."
}
Or ( In case only a Location Description is provided )
{
"_id" : ObjectId("5680e1c30a73fc5b0a81f29a"),
"LocDescription" : "Going North, take a right at the Eaton Ave & Kennedy Drive. Take the Overpass to Gaitherburg."
}
Or ( In case only a latitude and longitude are provided )
{
"_id" : ObjectId("567f90bc0a73fc5b0a81f231"),
"lat" : 184,
"lng" : 22
}
Could someone please tell me how I could modify the C# POCO Location class, and it's correponding mapping in the Global.asax.cs file so that the aforementioned features of saving can be carried out? I really want to avoid using Null or Nullable types.
Upvotes: 0
Views: 181
Reputation: 2576
Use BsonIgnoreIfDefaultAttribute
to mark class members whose default values shouldn't be serialized to DB.
In your case, it would be like:
public class Location
{
public Object Id { get; set; }
[BsonIgnoreIfDefault]
public double latitude { get; set; }
[BsonIgnoreIfDefault]
public double longitude { get; set; }
[BsonIgnoreIfDefault]
public String LocDescription { get; set; }
}
For string/nullable/object values you can also use BsonIgnoreIfNullAttribute
.
Upvotes: 2