3

I want to cast a realm collection to a list, then project it. However, doing this immediately triggers an error. The error I'm receiving is similar to this problem, and also this, but seems to be happening for a different (unknown) reason, since it appears the answers in those two questions don't apply to my condition (I'm using a newer version of Realm and I am not using a property accessor call in the predicate lambda).

I'm using my realm collection to project into a different type. I know that the current version of Realm (0.81.0) doesn't support .Select() so I am calling .ToList() and then projecting. The stack trace shows that the origin of the exception is the .ToList() call.

My Code:

private void BuildAndApplyBindingContext(int listId)
{
    realm.All<MemberInventoryItem>()
        .Where(i => i.InventoryListId == listId)
        .ToList()
        .Select(i => new ItemListEntryViewModel {
            Id = i.InventoryItemId,
            Type = i.IsAcquired ? InventoryType.Item : InventoryType.UnacquiredListItem,
            Name = i.Item,
            IsAcquired = i.IsAcquired,
            SubText = UiHelper.GetLocationString(i),
            BadgeText = UiHelper.GetBadgeText(i),
            ImageRef = UiHelper.SetMissingImage(i.ImageUrl),
            ExpiresDate = i.ExpiresDate,
            ShowNoticeText = i.ExpiresDate < DateTime.Now
            }).OrderBy(i => i.Name)
        .ToList()
    };

    ...
}

I get the following error:

System.NotSupportedException: The rhs of the binary operator 'Equal' should be a constant or closure variable expression. 
Unable to process `Convert(value(Prepify.App.Pages.Inventory.ListDetail.DetailTab+<>c__DisplayClass7_0).listId)`

Something to note, and I have no idea if it matters or not, but the property InventoryListId in my .Where() clause is of type int?. Should this matter?

Using Realm Xamarin v0.81.0 on Forms/Android

Community
  • 1
  • 1
Britton
  • 183
  • 2
  • 10

1 Answers1

4

Something to note, and I have no idea if it matters or not, but the property InventoryListId in my .Where() clause is of type int?. Should this matter?

Good that you thought to include that in your question. It would make sense that it matters. It means your

.Where(i => i.InventoryListId == listId)

is actually

.Where(i => i.InventoryListId == (int?)listId)

and this conversion is present in the generated expression tree. That's why you're seeing Convert(...) in the exception message.

Your LINQ provider's exception message says it requires either a constant or a closure variable expression, and a converted closure variable expression is neither.

And that's avoidable the same way as in the question you link to: explicitly store it in a local variable instead.

private void BuildAndApplyBindingContext(int listId)
{
    int? listIdNullable = listId;
    realm.All<MemberInventoryItem>()
        .Where(i => i.InventoryListId == listIdNullable)
        ...