问题
I want to get all elements where the Modified property isn't set but can't seem to get it to work with Realm.
Sample Code:
public class FooModel : RealmObject
{
public DateTimeOffset? Modified { get; set; }
}
...
public List<FooModel> GetAllUnmodified()
{
var realm = Realm.GetInstance();
//doesn't work
var result1 = realm.All<FooModel>().Where(model => model.Modified == null).ToList();
//doesn't work
var result2 = realm.All<FooModel>().Where(model => !model.Modified.HasValue).ToList();
//doesn't work
DateTimeOffset? testValue = null;
var result3 = realm.All<FooModel>().Where(model => model.Modified == testValue).ToList();
//doesn't work
var result4 = realm.All<FooModel>().Where(model => model.Modified == default(DateTimeOffset?)).ToList();
return result1;
}
Always getting System.NotSupportedException: The rhs of the binary operator 'Equal' should be a constant or closure variable expression.
or System.NotSupportedException: The member 'HasValue' is not supported
Did I miss anything? Is there a good way to see what actually is supported by Realm's Linq?
Using Realm Xamarin v0.77.1 on Android
EDIT:
I did try creating a linq expression tree as suggested by a commenter. This resulted in a System.MissingMethodException: Method 'RealmResults'1.get_Provider' not found.
exception.
回答1:
This feature is missing and high priority: #517. We are very aware that we have a number of LINQ shortcomings, we are looking into that whole area, including writing a summary about what features are supported, in the near future.
回答2:
Note for anyone seeing this later - this feature was added in version 0.77.0 and is live in the current 0.78.1.
We now support comparison to null.
public class Person : RealmObject
{
public bool? IsAmbivalent { get; set; }
...
_realm.All<Person>().Where(p => p.IsAmbivalent == null);
Or, for string properties, also checking:
_realm.All<Person>().Where(p => string.IsNullOrEmpty(p.OptionalAddress));
See unit tests for more examples
来源:https://stackoverflow.com/questions/38763893/how-to-check-for-null-on-nullable-types-using-linq-expression-in-realm