如何加入 LiteDb

How to Join In LiteDb

我如何在 LiteDb 中加入两个 table Like SQL 示例:我有两个 table 用户和 ActivityLog

这是模型

public class ActivityLog
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string Action { get; set; }
    public DateTime ActionDateTime { get; set; }
}


public class User
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string UserName { get; set; }
    public DateTime LoginDate { get; set; }

}

我需要加入 Activity.UserID = User.UserId。 有什么办法加入like sql

来自官方documentation

LiteDB is a document database, so there is no JOIN between collections. If you need reference a document in another document you can use DbRef. This document reference can be loaded when the database is initialized or when a query is run, or after a query is finished.

对于你的情况,你可以这样做

public class ActivityLog
{
    [BsonId]
    public int Id { get; set; }
    public DbRef<User> User { get; set; }
    public string Action { get; set; }
    public DateTime ActionDateTime { get; set; }
}


public class User
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string UserName { get; set; }
    public DateTime LoginDate { get; set; }

}


//usage
// Getting user and activityLog collections
var usersCollection = db.GetCollection<User>("Users");
var activityLogsCollection = db.GetCollection<ActivityLog>("ActivityLogs");

// Creating a new User instance
var user = new User { UserId = 5, ...};
usersCollection.Insert(user);

// Create a instance of ActivityLog and reference to User John
var activityLog = new ActivityLog
{
    OrderNumber = 1,
    OrderDate = DateTime.Now,
    //Add it by DbRef
    User = new DbRef<User>(usersCollection, user.UserId)
};
activityLogsCollection.Insert(activityLog)

有关详细信息,请参阅文档。