[CSHARP-767] Add an overload of SetDefaultValue that supports creating a new instance of the default value each time Created: 28/Jun/13  Updated: 20/Mar/14  Resolved: 01/Jul/13

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 1.8.1
Fix Version/s: 1.8.2

Type: Bug Priority: Major - P3
Reporter: Robert Stam Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to CSHARP-765 DOCS: Convention for ignoring all emp... Closed
Backwards Compatibility: Fully Compatible

 Description   

There is a problem using SetDefaultValue with mutable classes, because nothing protects the default value from being changed. For example, assume that the default value for L has been set to an empty list:

public class C
{
    public int Id { get; set; }
    public List<int> L { get; set; }
}
 
BsonClassMap.RegisterClassMap<C>(cm =>
{
    cm.AutoMap();
    cm.GetMemberMap(c => c.L).SetDefaultValue(new List<int>());
});

Then the following innocent looking code alters the default value:

var c1 = BsonSerializer.Deserialize<C>("{ _id : 1 }");
c1.L.Add(1);
var c2 = BsonSerializer.Deserialize<C>("{ _id : 1 }");

The call to c1.L.Add(1) has altered the default value, so c2 no longer has an empty list as the value of L.

The proposed alternative is to provide an additional overload of SetDefaultValue that allows you to provide a delegate that will create a new instance of the default value each time. For example:

BsonClassMap.RegisterClassMap<C>(cm =>
{
    cm.AutoMap();
    cm.GetMemberMap(c => c.L).SetDefaultValue(() => new List<int>());
});



 Comments   
Comment by auto [ 01/Jul/13 ]

Author:

{u'username': u'rstam', u'name': u'rstam', u'email': u'robert@10gen.com'}

Message: CSHARP-767: Changed new SetDefaultValue overload to check if the member map is frozen.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/aa842e9e677f82837258f48ed3774ccb120de309

Comment by auto [ 01/Jul/13 ]

Author:

{u'username': u'rstam', u'name': u'rstam', u'email': u'robert@10gen.com'}

Message: CSHARP-767: Added additional unit test that matches scenario described in the JIRA ticket.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/934b07641dd8bb26e524b8c24c32accf1a928aab

Comment by auto [ 01/Jul/13 ]

Author:

{u'username': u'rstam', u'name': u'rstam', u'email': u'robert@10gen.com'}

Message: CSHARP-767: Support a default value creator so that we can safely support default values of mutable classes.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/391093a4cfb11827d44795b6d6aaf4226b0ad884

Generated at Wed Feb 07 21:37:46 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.