[CSHARP-2080] Cannot translate simple expression: InvalidOperationException Created: 31/Oct/17  Updated: 17/Nov/22

Status: Backlog
Project: C# Driver
Component/s: Linq, LINQ3
Affects Version/s: 2.2.4
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Svetoslav Milenov Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: triaged
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 10 x64, IIS.



 Description   

The exception occurs in the method GetFieldExpression, for the following expression:
e => ((e.GetType() == BusinessPartner) AndAlso (e.PrivateExchangeId == "something"))

The code triggering the exception is:

var documentSerializer = BsonSerializer.SerializerRegistry.GetSerializer<T>();
var renderedFilter = filterDefinition.Render(documentSerializer, BsonSerializer.SerializerRegistry).ToString(); // the exception occurs in Render

The filter definition is of type MongoDB.Driver.AndFilterDefinition<BusinessPartner>, and has as expression the expression provided above.



 Comments   
Comment by Svetoslav Milenov [ 31/Oct/17 ]

Ok, I did a dirty workaround:

public static Expression<Func<TClass, bool>> CreateIsOfTypeExpression<TClass>(Type typeToMatch)
        {
            var type = Expression.Parameter(typeof(TClass), "type");
            var @is = Expression.TypeIs(type, typeToMatch);
            return Expression.Lambda<Func<TClass, bool>>(@is, type);
        }

Comment by Svetoslav Milenov [ 31/Oct/17 ]

The original issue CSHARP-1714 was closed with the suggestion to use "is" operator instead of e.GetType().

I have the same issue as the lass comment: https://jira.mongodb.org/browse/CSHARP-1714?focusedCommentId=1564402&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1564402

I.e. I have a type passed in runtime, so using "is" operator is not an option.

This used to work in the legacy driver.

What would be the workaround?

Generated at Wed Feb 07 21:41:33 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.