[CSHARP-2111] Expression based queries don't work for properties without a setter Created: 24/Nov/17  Updated: 08/Feb/23

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

Type: Bug Priority: Major - P3
Reporter: Daniel Hegener Assignee: Unassigned
Resolution: Unresolved Votes: 1
Labels: triaged
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

When trying to issue a query using an expression that contains a property with no setter the serialization fails:

An unhandled exception of type 'System.InvalidOperationException' occurred in MongoDB.Driver.dll
 
Additional information: {document}.PropertyThatDoesNotWork is not supported.

Here is some test code that demonstrates the issue:

    public class Test
    {
        public ObjectId Id { get; set; }
        public string Field;
        public string PropertyThatWorks { get; set; }
        public string PropertyThatDoesNotWork { get; }
    }
 
    class Program
    {
        private static readonly IMongoCollection<Test> collection = new MongoClient().GetDatabase("test").GetCollection<Test>("c");
        
        static void Main(string[] args)
        {
            /* 1 - works */ var result = collection.Find(c => c.Field == "test").ToList();
            /* 2 - works */ result = collection.Find(c => c.PropertyThatWorks == "test").ToList();
            /* 3 - FAILS */ result = collection.Find(c => c.PropertyThatDoesNotWork == "test").ToList();
        }
    }



 Comments   
Comment by James Kovacs [ 10/Feb/22 ]

Note that this will work if you declare the property with a private or init-only setter.

class Test
{
        public ObjectId Id { get; set; }
        public string Field;
        public string PropertyThatWorks { get; set; }
        public string PropertyThatDoesNotWork { get; }
        public string PropertyWithPrivateSetterThatWorks { get; private set; }
        public string PropertyWithInitOnlySetterThatWorks { get; init set; }
}

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