Reputation: 424
Simple question how do you set the default value of a BsonValue to an empty List
[BsonElement("Networks")]
[BsonRepresentation(BsonType.String)]
[BsonIgnoreIfNull]
[BsonDefaultValue(new List<SocialProfileTypes>() { })]
[BsonIgnoreIfDefault]
public UniqueList<SocialProfileTypes> Networks
{
get { return networks; }
set { networks = value; }
}
As [BsonDefaultValue(new List<SocialProfileTypes>() { })]
gives a syntax error
Error 8 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Upvotes: 3
Views: 2851
Reputation: 21
I solved my similar problem.
My Startup.cs file
public class Startup
{
// Other codes .....
public void ConfigureServices(IServiceCollection services)
{
// Other codes .....
// Register custom array serializer
BsonSerializer.RegisterGenericSerializerDefinition(typeof(IEnumerable<>), typeof(MongoDBCustomArraySerializer<>));
// Other codes .....
}
}
My CustomSerializer
public class MongoDBCustomArraySerializer<T> : ArraySerializer<T>
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, T[] value)
{
// Serializer empty array when array is null
if (value == null)
base.Serialize(context, args, Array.Empty<T>());
else
base.Serialize(context, args, value);
}
}
Upvotes: 0
Reputation: 12624
This is a C# language constraint. Values in attributes must be compile time constants.
With regards to the mongodb driver, you'll need to use code to set the value like this (note: have no compiled this, but it will be similar)
BsonClassMap.RegisterClassMap<MyClass>(cm =>
cm.AutoMap();
cm.MapMember(x => x.Networks).SetDefaultValue(new List<SocialProfileTypes>())
});
I believe this is going to fail anyways because List doesn't implement or inherit from UniqueList, so you'll have to fix that too.
Upvotes: 2