【问题标题】:How to Join In LiteDb如何加入 LiteDb
【发布时间】:2017-06-21 12:07:23
【问题描述】:

我如何在 LiteDb 中的两个表之间加入 SQL 之类的 示例:我有两个表 User 和 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一样加入

【问题讨论】:

    标签: c# linq c#-4.0 c#-3.0 litedb


    【解决方案1】:

    来自官方documentation

    LiteDB是一个文档数据库,所以之间没有JOIN 收藏品。如果您需要参考另一个文档中的文档,您可以 可以使用 DbRef。当 数据库初始化或查询运行时,或查询完成后 完成了。

    在你的情况下,你可以这样做

    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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2020-04-17
      • 2018-06-08
      相关资源
      最近更新 更多