[CSHARP-3922] LINQ3: support calls to constructors in Select Created: 20/Oct/21  Updated: 28/Oct/23  Resolved: 21/Jun/22

Status: Closed
Project: C# Driver
Component/s: LINQ3
Affects Version/s: None
Fix Version/s: 2.16.1

Type: Task Priority: Unknown
Reporter: Boris Dogadov Assignee: Robert Stam
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
is depended on by CSHARP-3923 Improve exception message when using ... Closed
is depended on by CSHARP-3924 Support Tuples in LINQ3 Closed
Duplicate
is duplicated by CSHARP-1691 Select with create new object throw e... Closed
is duplicated by CSHARP-4180 Correct handling NewExpression.Member... Closed

 Description   

Support expressions like: 

queryable().Select(_ => new KeyValuePair(...))

Note: after investigation I'm modifying the description of this ticket to make it more general to refer to the use of any constructor call in Select statement. The current implementation assumes that any `NewExpression` is the creation of an anonymous type value, but that's not always true.

The following test case illustrates a simple case of the more general problem to be solved:

[Fact]
public void Select_with_constructor_call_should_work()
{
    var client = DriverTestConfiguration.Linq3Client;
    var database = client.GetDatabase("test");
    var collection = database.GetCollection<C>("test");
 
    var queryable = collection.AsQueryable()
        .Select(c => new D(c.X));
 
    var stages = Linq3TestHelpers.Translate(collection, queryable);
    var expectedStages = new[]
    {
        "{ $project : { Y : '$X', _id : 0 } }"
    };
    Linq3TestHelpers.AssertStages(stages, expectedStages);
}
 
private class C
{
    public int Id { get; set; }
    public int X { get; set; }
}
 
private class D
{
    public D(int y)
    {
        Y = y;
    }
 
    public int Y { get; set; }
}



 Comments   
Comment by Githook User [ 21/Jun/22 ]

Author:

{'name': 'rstam', 'email': 'robert@robertstam.org', 'username': 'rstam'}

Message: CSHARP-3922: LINQ3: support calls to constructors in Select.
Branch: v2.16.x
https://github.com/mongodb/mongo-csharp-driver/commit/269d2244987a443e71babe56357a96473c2f5eff

Comment by Githook User [ 21/Jun/22 ]

Author:

{'name': 'rstam', 'email': 'robert@robertstam.org', 'username': 'rstam'}

Message: CSHARP-3922: LINQ3: support calls to constructors in Select.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/94f3440e8e68f691e08f3899b2c7c5708c0f7000

Comment by Robert Stam [ 20/Oct/21 ]

To implement this we will have to know how the class being constructed is serialized. Most likely this will require mapping each constructor argument to the corresponding property so that we can figure out the element names in the computed document.

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