如何加入LiteDb [英] How to Join In LiteDb

查看:195
本文介绍了如何加入LiteDb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像SQL一样在LiteDb中的两个表之间联接 示例:我有两个表User和ActivityLog

How can i join between two table in LiteDb Like SQL Example : I Have Two table User and 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. 有没有办法像sql一样

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

推荐答案

来自官方文档

LiteDB是一个文档数据库,因此之间没有JOIN 集合.如果您需要在另一个文档中引用一个文档,则可以 可以使用DbRef.可以在 数据库已初始化或在运行查询时或在执行查询后 完成.

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.

这篇关于如何加入LiteDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆