ID does not increment when inserting
class Test
{
[BsonId]
public ulong ID { get; set }
publi string Name { get; set }
}
using ulong as datatype for ID does not increment, and results with an exception.
Can you provide some sample? Minimal code to run and reproduce the issue.
@FDemin Can you also provide us with some extra information like which version of LiteDB that you're using and which OS that you're trying to run it on?
having a property name Id works on auto-incrementing
however, having a different property name (ID, <Model Name>ID), even having a [BsonId] attribute, auto-increment doesn't work
@FDemin Auto-id only supports types Int32, Int64, ObjectId and Guid. In fact, the BSON spec doesn't even support UInt64 as a valid type for an element in a BSON (our serializer converts it to Int64).
Question about this.
I've tested it with Id as a long and I can see it creates a json object instead of a number.
If I use int, it creates a number.
Both seems to auto-increment correctly, but.. how do I get to use the long as a number and not as an object with a number embedded?
See the following snapshot of a sample ran first with long and then with int
@sunnyatticsoftware LiteDB uses BSON serialization when storing data, which means that, internally, both int32 and int64 are stored in binary form. However, BSON is a superset of JSON – JSON only has a "number" type, while BSON has distinct types for int32, int64, double and decimal. So, in order to preserve the type of the value when converting a BSON to JSON, we use custom formats:
int32is represented by number with no decimal places (e.g.:3);doubleis represented by a number with decimal places (e.g.:3.0);int64is represented by a document with the following structure:{"$numberLong":"3"}decimalis represented by a document with the following structure:{"$numberDecimal":"3"}
If you want to display only the numerical value of longs, you could do something like this: SELECT INT32($._id), Type, ... FROM events.
Auto-id works for int, long, Guid and ObjectId ids, and ulong isn't one of them. BSON has no unsigned 64-bit type, so a ulong is stored as Int64, and the collection doesn't treat its 0 as "empty" (source). The first entity is saved with _id = 0, and the next one fails with a duplicate key. Use long for the id if you want auto-increment, or assign ulong ids yourself.
On the naming question: [BsonId] works on a property with any name, so [BsonId] public int ID { get; set; } auto-increments. Without the attribute, the id is picked by name, case-insensitively: Id or <ClassName>Id (e.g. TestId for class Test). Any other name is stored as a normal field, and a separate ObjectId _id is generated.
The {"$numberLong":"1"} form for long ids is LiteDB's extended JSON for Int64 values, also intended.
If this doesn't cover your case, comment here and we'll reopen it.