英文:
In litedb,How can I get the _id value?
问题
I want to get the _id value 642ec0a9f6aecc035cd15f5e
Is there any way?
英文:
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?
答案1
得分: 1
你可以尝试以这种方式进行。
在你的模型中插入ID属性也。
public class Account
{
public Guid ID { get; set; }
public string? Username { get; set; }
public string? Password { get; set; }
}
然后生成一个新的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());
}
从LiteDB文档中了解,AutoId只在文档插入时没有_id字段时使用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论