Realm Xamarin LINQ Object

只愿长相守 提交于 2019-12-04 04:50:28

问题


What is the correct way to query Realm with LINQ where the query includes fields from other Realm objects? For example:

public class Department : RealmObject
{
    [Primary Key]
    public string UniqueId { get; set; }
}

public class Employee : RealmObject
{
    [Primary Key]
    public string Name { get; set; }

    // Parent
    public Department Department { get; set; }
}

Then I would expect to be able to do something like:

var employee = realm.All<Employee>().SingleOrDefault( e => e.Department.UniqueId == fooId && e.Name == fooName );

But this always returns no matches. Where() also returns no matches. However, eliminating the e.Department and searching only on employee name works fine but obviously does not scope to Department as intended.

This is with the latest Realm Xamarin 0.80.

What am I doing wrong?


回答1:


Querying by nested RealmObjects attributes is not currently supported:

Just to clarify here, we don't yet support queries on related objects like this. We will in the future, but there is no timeline at the moment.

The following is also not currently supported:

var deptFilter = theRealm.ObjectForPrimaryKey<Department>("HR");
var employeesByDept = theRealm.All<Employee>().Where((Employee emp) => emp.Department == deptFilter & emp.Name == "StackOverflow");

The left-hand side of the And operator must be a direct access to a persisted property in Realm. Unable to process '(emp.Department == value(Realm080.App+c__AnonStorey1).deptFilter)'.

You can do direct RealmObject equalities, just not in the same Linq expression, so break it down further into a sub-query.

Example of how I currently do it:

var deptFilter = theRealm.ObjectForPrimaryKey<Department>("HR");
var employeesByDept = theRealm.All<Employee>().Where((Employee emp) => emp.Department == deptFilter);
var employees = employeesByDept.Where((Employee emp) => emp.Name == "StackOverflow");
foreach (var emp in employees)
{
    D.WriteLine(emp.Name);
}

Note: https://github.com/realm/realm-dotnet/issues/723



来源:https://stackoverflow.com/questions/40330887/realm-xamarin-linq-object

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