建立正确的领域子查询

时间:2018-12-17 09:31:08

标签: c# realm subquery

我有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

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

您好,安德鲁(Andrew),您可以使用LINQ by(p)轻松做到(但有点脏)

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

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