As shown below, I inserted an element into the document, and it automatically generated an _id of type Object for me. So how do I use the existing model to get the value of this _id?
using LiteDB;
using (var db = new LiteDatabase(@"C:\litedb\test.db"))
{
var accountCollection = db.GetCollection<Account>("Account");
Account account = new Account
{
Username = "root",
Password = "123456"
};
accountCollection.Insert(account);
//{
// "_id": { "$oid": "642ec0a9f6aecc035cd15f5e"},
// "Username": "root",
// "Password": "123456"
//}
}
public class Account
{
public string? Username { get; set; }
public string? Password { get; set; }
}
I want to get the _id value 642ec0a9f6aecc035cd15f5e Is there any way?
you can try in this way instead.
Insert in your model the ID property also.
public class Account
{
public Guid ID {get;set;}
public string? Username { get; set; }
public string? Password { get; set; }
}
Then generate a new ID.
using (var db = new LiteDatabase(@"C:\litedb\test.db"))
{
var accountCollection = db.GetCollection<Account>("Account");
Account account = new Account
{
ID = Guid.NewGuid(),
Username = "root",
Password = "123456"
};
accountCollection.Insert(account);
Console.WriteLine(account.ID.ToString());
}
From LiteDB documentation AutoId is only used when there is no _id field in the document upon insertion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With