Skip to content

Commit bd1a156

Browse files
author
Hugo Bonacci
committed
Adjusted the way that IDs are generated
1 parent 065dd45 commit bd1a156

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

MongoDocument.cs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,30 @@ public MongoOid GenerateId() {
105105
/// The Oid for a document (if any)
106106
/// </summary>
107107
public MongoOid Id {
108-
get { return this.Get<MongoOid>(Mongo.DocumentIdKey, new MongoOid()); }
108+
get {
109+
110+
//if no id has been generated, do it now
111+
MongoOid id = this.Get<MongoOid>(Mongo.DocumentIdKey, null);
112+
if (id == null) {
113+
id = new MongoOid();
114+
this.Set(Mongo.DocumentIdKey, id);
115+
}
116+
117+
//return the id to use
118+
return id;
119+
120+
}
109121
set {
122+
123+
//if trying to assign anything that isn't a MongoOid
124+
//then complain about it
110125
if (value != null && !(value is MongoOid)) {
111126
throw new ArgumentException("You can only assign a MongoOid as the Id for a MongoDocument");
112127
}
128+
129+
//update the value
113130
this.Set<MongoOid>(Mongo.DocumentIdKey, value);
131+
114132
}
115133
}
116134

@@ -129,14 +147,14 @@ protected override IEnumerable<BsonFieldDetail> OnBeforeFinishBsonRender(IEnumer
129147
//get all of the ids to use
130148
IEnumerable<BsonFieldDetail> ids = fields.Where(item => item.Type is MongoOidType);
131149
list.RemoveAll(item => item.Type is MongoOidType);
150+
list = list.OrderBy(item => item.Length).ToList();
132151

133152
//because the items are shared in the same list
134153
//we have to insert these one at the time since
135154
//if we use AddRange an exception will be thrown
136155
//since the list is modified while enumerating
137156
//through the values. We're also going backwards
138157
//to make sure they retain their original order
139-
list = list.OrderBy(item => item.Length).ToList();
140158
for (int index = ids.Count(); index-- > 0; ) {
141159
list.Insert(0, ids.ElementAt(index));
142160
}

0 commit comments

Comments
 (0)