Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm Xamarin LINQ Object

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?

like image 976
BSohl Avatar asked Sep 16 '25 22:09

BSohl


1 Answers

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

like image 144
SushiHangover Avatar answered Sep 19 '25 18:09

SushiHangover