【问题标题】:Build correct realm Subquery建立正确的领域子查询
【发布时间】:2023-03-06 15:28:02
【问题描述】:

我有 2 个表:Quest 和 HistoryItem;

简化任务:

public class Quest : RealmObject
{
    [PrimaryKey]
    public string Id { get; set; } = Guid.NewGuid().ToString();

    public string Name { get; set; }

    public int MaxRepeats { get; set; }        
}

简化历史:

public class HistoryItem : RealmObject
{
    [PrimaryKey]
    public string Id { get; set; } = Guid.NewGuid().ToString();

    public DateTimeOffset DoneTime { get; set; }

    public Quest Quest { get; set; }
}

如何正确编写领域子查询以显示所有已完成少于 questItem.MaxRepeats 的任务?如果每个完成的任务都将添加到新的 HistoryItem.Quest 字段中;

据我了解,它一定是这样的:

_db.Realm.All<Quest>().Filter($"SUBQUERY(HistoryItem, $hi, $hi.Quest).@count > $hi.Quest.MaxRepeats");

但由于某种原因没有正确过滤=(

Realms.Exceptions.RealmException: 'SUBQUERY(HistoryItem, $hi, $hi.Quest).@count > $hi.Quest.MaxRepeats:1:8(8): 无效谓词。'

此子查询是基于documentation 示例编写的:

realm.All<Person>().Filter("SUBQUERY(Dogs, $dog, $dog.Vaccinated == false).@count > 3");
// find all people who have more than 3 unvaccinated dogs.

也许,这里会有一些有用的信息NSPredicateCheatsheet 或这里js filter usage samples

【问题讨论】:

    标签: c# realm subquery


    【解决方案1】:

    你需要在QuestHistoryItem之间建立链接:

    public class Quest : RealmObject
    {
        [PrimaryKey]
        public string Id { get; set; } = Guid.NewGuid().ToString();
    
        public string Name { get; set; }
    
        public int MaxRepeats { get; set; } 
    
        [Backlink(nameof(HistoryItem.Quest))]
        public IQueryable<HistoryItem> HistoryItems{ get; }       
    }
    
    public class HistoryItem : RealmObject
    {
        [PrimaryKey]
        public string Id { get; set; } = Guid.NewGuid().ToString();
    
        public DateTimeOffset DoneTime { get; set; }
    
        public Quest Quest { get; set; }
    }
    

    然后你可以使用LINQ 来查询任务:

    _db.Realm.All<Quest>().Filter("HistoryItems.@count <= MaxRepeats");
    

    【讨论】:

    • 谓词仍然不正确...我也尝试过"SUBQUERY(HistoryItem, $hi, $hi.Quest == Quest).@count &lt;= MaxRepeats",但结果仍然相同 - 谓词不正确...
    • Realms.Exceptions.RealmException: 'No property 'HistoryItem' on object of type 'Quest''
    • 所以您在QuestHistoryItem 之间没有链接?如果你有它们之间的链接,查询起来会更容易。我将通过链接更新我的答案
    • HistoryItem 有一个字段 HistoryItem.Quest。您可以在我的问题的 HistoryItem 类中看到它。所以他们是联系在一起的
    • 不,我的意思是QuestHistoryItem的反向链接
    【解决方案2】:

    嗨,Andrew,您可以使用 LINQ 轻松做到这一点(但有点脏)

    _db.Realm.All<Quest>().Where(p=>_db.Realm.All<HistoryItem>().Count(u=>U.Quest==p)<p.MaxRepeats)
    

    如您所见,我们必须先获取 HistoryItem.Count。

    【讨论】:

    • 此解决方案将在数据库上产生额外的性能负载,因此通常不是最佳解决方案,但这必须适用于一些小型数据库。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    相关资源
    最近更新 更多