How to Join In LiteDb

不羁的心 提交于 2020-07-22 09:33:24

问题


How can i join between two table in LiteDb Like SQL Example : I Have Two table User and ActivityLog

Here is the Model

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; }

}

I need to join Activity.UserID = User.UserId. Is there any way to join like sql


回答1:


From official 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.

In your case, you can do smth like

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)

See the documentation for more details.



来源:https://stackoverflow.com/questions/44675677/how-to-join-in-litedb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!