Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Dec 6, 2025

Summary

This PR fixes three issues with nested SelectExpr code generation as reported in the issue:

✅ Issue 1: Missing Parent Class Qualification

Problem: When using nested SelectExpr with explicit DTO types declared inside a parent class, the generated code referenced them without the parent class qualifier, causing compilation errors.

Solution:

  • Updated DtoProperty.cs to extract parent class information from the syntax tree when the type symbol is not available (error type)
  • Simplified logic in SelectExprInfo.cs to use ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) for fully qualified names
  • Updated GenerateDtoClassInfo.cs to preserve global:: prefix in generic type arguments

Example: NestedItemDtoEnumerableglobal::MinRepro.Issue_NestedSelectExprTest.NestedItemDtoEnumerable

✅ Issue 2: Array Property Type Missing [] Suffix

Problem: When using .ToArray() with nested SelectExpr, the generated DTO property type was missing the array suffix [].

Solution:

  • Created IsArrayType helper method in GenerateDtoClassInfo.cs that checks:
    1. Type symbol (IArrayTypeSymbol)
    2. Type string pattern (ends with [])
    3. Original expression syntax (ends with .ToArray())

Example: NestedItemDtoArrayNestedItemDtoArray[]

✅ Issue 3: Verbose Documentation Comments

Problem: SelectExpr method calls in documentation comments included full generic type arguments and lambda bodies, making them overly verbose.

Solution:

  • Updated AbbreviateAllMethodCalls in DtoProperty.cs to detect and skip generic type arguments when abbreviating method calls
  • Extracted SkipGenericTypeArguments helper method for better code organization
  • Comments now follow the same abbreviated pattern as regular Select calls

Example: SelectExpr<TIn,TResult>(lambda)SelectExpr(...)

Review Comments Addressed

Test File Updates

  • Renamed test file to Issue217_NestedSelectExprTest.cs per naming convention
  • Removed explicit qualifiers from SelectExpr calls (e.g., Issue_NestedSelectExprTest.NestedItemDtoEnumerableNestedItemDtoEnumerable)
  • Added partial class declarations for all nested DTOs to make them visible without qualification

Code Quality Improvements

  • Enhanced comment on IsArrayType helper to clarify that .ToArray() detection is a necessary compromise when semantic model information is unavailable
  • Extracted SkipGenericTypeArguments helper method from AbbreviateAllMethodCalls for better separation of concerns

Important Note on Partial Class Declarations

Partial class declarations are required when using unqualified DTO type names in nested SelectExpr calls. Without them, the generator cannot determine if the DTO should be nested inside a parent class or placed at the namespace level, and defaults to namespace level placement.

Two approaches work:

  1. With partial declarations (recommended): Declare partial classes inside the parent class, allowing unqualified type names
  2. With qualified names: Use fully qualified names like Issue_NestedSelectExprTest.NestedItemDtoEnumerable in the SelectExpr type arguments

The test demonstrates approach #1 for cleaner code.

Testing

  • All 130 tests passing ✅
  • Test case validates unqualified DTO type references work correctly with partial class declarations
  • No regressions in existing tests
Original prompt

This section details on the original issue you should resolve

<issue_title>bug: The code generated for nested SelectExpr is still insufficient</issue_title>
<issue_description>### Minimal Reproducible Example

using System.Collections.Generic;
using System.Linq;

namespace MinRepro;

public partial class Issue_NestedSelectExprTest
{
    private readonly List<NestedEntity> TestData = [];

    public void NestedSelectExpr_WithExplicitDtoTypes_ShouldWork()
    {
        var query = TestData.AsQueryable();

        var result = query
            .SelectExpr<NestedEntity, NestedEntityDto>(x => new
            {
                x.Id,
                x.Name,
                // error: ItemsEnumerable should be IEnumerable<NestedItemDtoEnumerable>
                ItemsEnumerable = x.Items.SelectExpr<NestedItem, NestedItemDtoEnumerable>(i => new
                {
                    i.Id,
                }),
                ItemsList = x
                    .Items.SelectExpr<NestedItem, NestedItemDtoList>(i => new { i.Id })
                    .ToList(),
                // error: ItemsArray should be NestedItemDtoArray[]
                ItemsArray = x
                    .Items.SelectExpr<NestedItem, NestedItemDtoArray>(i => new
                    {
                        i.Id,
                        i.Title,
                        SubItem = i.SubItems.Select(si => new { si.Id, si.Value }),
                        // error: SubItemWithExpr should be IEnumerable<NestedSubItemDto>
                        SubItemWithExpr = i.SubItems.SelectExpr<NestedSubItem, NestedSubItemDto>(
                            si => new { si.Id, si.Value }
                        ),
                    })
                    .ToArray(),
            })
            .ToList();
    }

    internal class NestedEntity
    {
        public int Id { get; set; }
        public string Name { get; set; } = null!;
        public List<NestedItem> Items { get; set; } = [];
    }

    internal class NestedItem
    {
        public int Id { get; set; }
        public string Title { get; set; } = null!;
        public List<NestedSubItem> SubItems { get; set; } = [];
    }

    internal class NestedSubItem
    {
        public int Id { get; set; }
        public string Value { get; set; } = null!;
    }

    internal partial class NestedEntityDto;
}

Generated Output

// <auto-generated>
// This file is auto-generated by Linqraft.
//   Linqraft Version  : 0.7.0-alpha.8+19d8834e72
//   Linqraft Build at : 2025-12-06 21:57:55
//   Code Generated at : 2025-12-06 22:22:54
// </auto-generated>
#nullable enable
#pragma warning disable IDE0060
#pragma warning disable CS8601
#pragma warning disable CS8602
#pragma warning disable CS8603
#pragma warning disable CS8604
#pragma warning disable CS8618
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Linqraft
{
    file static partial class GeneratedExpression
    {
        /// <summary>
        /// generated select expression method NestedEntityDto (explicit) <br/>
        /// at Program.cs(15,14)
        /// </summary>
        [global::System.Runtime.CompilerServices.InterceptsLocationAttribute(1, "kJHmE9posoDZvhZUfQzD2lMBAABQcm9ncmFtLmNz")]
        public static IQueryable<TResult> SelectExpr_785FB844_EC5ADE1A<TIn, TResult>(
            this IQueryable<TIn> query, Func<TIn, object> selector)
        {
            var matchedQuery = query as object as IQueryable<global::MinRepro.Issue_NestedSelectExprTest.NestedEntity>;
            var converted = matchedQuery.Select(x => new global::MinRepro.Issue_NestedSelectExprTest.NestedEntityDto
            {
                Id = x.Id,
                Name = x.Name,
                ItemsEnumerable = x.Items
                    .Select(i => new global::MinRepro.NestedItemDtoEnumerable
                    {
                        Id = i.Id
                    }),
                ItemsList = x.Items
                    .Select(i => new global::MinRepro.NestedItemDtoList
                    {
                        Id = i.Id
                    })
                    .ToList(),
                ItemsArray = x.Items
                    .Select(i => new global::MinRepro.NestedItemDtoArray
                    {
                        Id = i.Id,
                        Title = i.Title,
                        SubItem = i.SubItems
                            .Select(si => new global::MinRepro.LinqraftGenerated_15C8F54D.Issue_NestedSelectExprTest.SubItemDto
                            {
                                Id = si.Id,
                                Value = si.Value
                            }),
                        SubItemWithExpr = i.SubItems
                            .Select(si => new global::MinRepro.NestedSubItemDto
                            {
                                Id = si.Id,
                                Value = si.Value
                      ...

</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes arika0093/Linqraft#217

<!-- START COPILOT CODING AGENT TIPS -->
---

💬 We'd love your input! Share your thoughts on Copilot coding agent in our [2 minute survey](https://gh.io/copilot-coding-agent-survey).

Copilot AI self-assigned this Dec 6, 2025
@coderabbitai
Copy link

coderabbitai bot commented Dec 6, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.


Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI changed the title [WIP] Fix bug with generated code for nested SelectExpr Fix nested SelectExpr code generation: parent class qualification, array types, and comment verbosity Dec 6, 2025
Copilot AI requested a review from arika0093 December 6, 2025 15:27
@arika0093 arika0093 linked an issue Dec 7, 2025 that may be closed by this pull request
Copy link
Owner

@arika0093 arika0093 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot Please fix the review comments.

…partial declarations, improve comments, extract method

Co-authored-by: arika0093 <[email protected]>
Copy link
Owner

@arika0093 arika0093 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot AI requested a review from arika0093 December 7, 2025 13:15
@arika0093 arika0093 marked this pull request as ready for review December 7, 2025 13:28
@arika0093 arika0093 merged commit a163791 into main Dec 7, 2025
7 checks passed
@arika0093 arika0093 deleted the copilot/fix-nested-select-expr-bug branch December 7, 2025 14:54
arika0093 added a commit that referenced this pull request Dec 10, 2025
…ray types, and comment verbosity (#222)

* Initial plan

* Initial analysis of nested SelectExpr issues

Co-authored-by: arika0093 <[email protected]>

* Fix Issues 1 and 3 for nested SelectExpr - Issue 2 still in progress

Co-authored-by: arika0093 <[email protected]>

* Fix Issue 2 - array property types now correctly include [] suffix

Co-authored-by: arika0093 <[email protected]>

* Refactor array type detection into helper method per code review

Co-authored-by: arika0093 <[email protected]>

* Address PR review comments: rename test file, remove qualifiers with partial declarations, improve comments, extract method

Co-authored-by: arika0093 <[email protected]>

* Clarify that partial class declarations are required for nested DTO generation

Co-authored-by: arika0093 <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: arika0093 <[email protected]>
(cherry picked from commit a163791)
@arika0093 arika0093 mentioned this pull request Dec 10, 2025
arika0093 added a commit that referenced this pull request Dec 10, 2025
* Fix: Remove parent class nesting from implicit DTOs in hash namespaces (#219)

* Initial plan

* Add test for issue: implicit DTOs should not be nested in parent class when using hash namespace

Co-authored-by: arika0093 <[email protected]>

* Fix: Implicit DTOs should not be nested in parent class when using hash namespace

Co-authored-by: arika0093 <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: arika0093 <[email protected]>
(cherry picked from commit dd2d380)

* Fix nested SelectExpr inconsistency between playground and source generator (#221)

* Initial plan

* Add shared IsNestedInsideAnotherSelectExpr helper and use in playground and source generator

Co-authored-by: arika0093 <[email protected]>

* Add comprehensive tests for nested SelectExpr consistency fix

Co-authored-by: arika0093 <[email protected]>

* Remove tests for nested SelectExpr type verification

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: arika0093 <[email protected]>
Co-authored-by: Arika Ishinami <[email protected]>
(cherry picked from commit a25737e)

* docs: Add IntroductionSection component and improve accessibility (#223)

* feat: add IntroductionSection component for query-based DTO generation

* fix: add translate attribute to improve accessibility in playground components

* refactor: remove custom animation definitions from tailwind.css

(cherry picked from commit 2a039c0)

* Fix nested SelectExpr code generation: parent class qualification, array types, and comment verbosity (#222)

* Initial plan

* Initial analysis of nested SelectExpr issues

Co-authored-by: arika0093 <[email protected]>

* Fix Issues 1 and 3 for nested SelectExpr - Issue 2 still in progress

Co-authored-by: arika0093 <[email protected]>

* Fix Issue 2 - array property types now correctly include [] suffix

Co-authored-by: arika0093 <[email protected]>

* Refactor array type detection into helper method per code review

Co-authored-by: arika0093 <[email protected]>

* Address PR review comments: rename test file, remove qualifiers with partial declarations, improve comments, extract method

Co-authored-by: arika0093 <[email protected]>

* Clarify that partial class declarations are required for nested DTO generation

Co-authored-by: arika0093 <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: arika0093 <[email protected]>
(cherry picked from commit a163791)

* docs: separate README contents to other files (#224)

(cherry picked from commit 29b0301)

* Fix: set default value of settingsExpanded to false in Sidebar component

(cherry picked from commit a34d686)

* docs: add comprehensive documentation for Nested SelectExpr feature

(cherry picked from commit 97439c9)

* Revert "docs: add comprehensive documentation for Nested SelectExpr feature"

This reverts commit 97439c9.

(cherry picked from commit 755698c)

* docs: add Nested SelectExpr documentation for reusable DTOs (#225)

* docs: add Nested SelectExpr documentation for reusable DTOs

* docs: update Nested SelectExpr documentation with important notes and usage requirements

* upd

* Fix GitHub Issue link in nested-selectexpr.md

(cherry picked from commit 64b9787)

* fix: NestedSelectExprTest and update documentation (#229)

* Fix: update Issue207_NestedSelectExprTest to support partial classes and remove .NET 9 specific warnings

* Fix: update documentation for Nested SelectExpr to clarify beta status and remove .NET 9+ recommendation

(cherry picked from commit 1aa5ec7)

* Document explicit class naming for nested DTOs

Added section on explicit class naming in nested DTOs.

(cherry picked from commit 1ddc079)

* Enhance library comparison with GitHub stars

Updated the library comparison table to include GitHub repository star counts for each library.

(cherry picked from commit d875f80)

* Update Docs link to point to library directory

(cherry picked from commit 59498e4)

* Refactor Order example to use records and facets

Updated the example to use records and facets for Order and OrderChild.

(cherry picked from commit c66f8b8)

* Add pre-built expression tree caching for IQueryable operations (#234)

* Initial plan

* Add pre-built expression tree configuration and implementation

- Added LinqraftUsePrebuildExpression configuration option (default: false)
- Created ExpressionTreeBuilder helper class for generating cached expression fields
- Updated SelectExprInfoAnonymous to use pre-built expressions when enabled
- Updated SelectExprInfoNamed to use pre-built expressions when enabled
- Updated SelectExprInfoExplicitDto to use pre-built expressions when enabled
- Pre-built expressions only apply to IQueryable (not IEnumerable)
- Pre-built expressions are disabled when captures are used

Co-authored-by: arika0093 <[email protected]>

* Refactor static field generation to class level

- Moved static field generation from method body to class level
- Added GenerateStaticFields() virtual method to SelectExprInfo
- Updated SelectExprGroups to collect and pass static fields
- Updated GenerateSourceCodeSnippets to output static fields before methods
- Fixed null reference warning in SelectExprGroups

Co-authored-by: arika0093 <[email protected]>

* Complete pre-built expression tree implementation

- Fixed CompilerVisibleProperty list to include LinqraftUsePrebuildExpression
- Anonymous types cannot use pre-built expressions (result type is compiler-generated)
- Pre-built expressions only work for named/predefined/explicit DTO types
- Added comprehensive tests for IQueryable with different DTO patterns
- All tests passing with pre-built expressions enabled

Co-authored-by: arika0093 <[email protected]>

* Add LinqraftUsePrebuildExpression to all CompilerVisibleProperty lists

- Updated examples/Directory.Build.props with new configuration property
- Fixed playground/Services/CodeGenerationService.cs to use updated API signature
- All projects now support the new LinqraftUsePrebuildExpression configuration

Co-authored-by: arika0093 <[email protected]>

* Add LinqraftUsePrebuildExpression property to project files

* Fix code generation issues per review feedback

- Use 'var' instead of explicit type in expression initialization (line 93)
- Remove unnecessary '!' null-forgiving operator when fieldName is not null
- Fix indentation of generated multi-line lambda expressions
- Use explicit Expression<> type instead of 'as' operator (lambdas cannot use 'as')

Co-authored-by: arika0093 <[email protected]>

* Refactor to use direct expression initialization per review feedback

- Updated documentation in global-properties.md for LinqraftUsePrebuildExpression
- Added note about captures not supporting pre-built expressions
- Refactored ExpressionTreeBuilder to directly initialize expression fields (no lazy init)
- Removed GenerateNamedExpressionTreeInitialization and GenerateAnonymousExpressionTreeInitialization
- Expression trees now initialized at field declaration, eliminating null checks
- Updated SelectExprInfoNamed and SelectExprInfoExplicitDto to use new approach
- Added test for multiple DTO types to verify pre-built expressions work correctly
- All 6 tests passing

Co-authored-by: arika0093 <[email protected]>

* Address final review feedback: readonly, indentation, remove test, add playground toggle

- Added 'readonly' keyword to static expression fields for immutability
- Fixed indentation: ensured proper line ending with AppendLine for multi-line expressions
- Deleted Linqraft.Tests.Configuration project as requested
- Removed project reference from Linqraft.slnx
- Added toggle for LinqraftUsePrebuildExpression in playground Settings section
- All tests passing (130/130)

Co-authored-by: arika0093 <[email protected]>

* revert: reset Linqraft.Tests.Configuration

* Fix indentation in BuildExprCodeSnippets for static fields

* Add static fields generation to expression code snippets

* formatt

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: arika0093 <[email protected]>
Co-authored-by: Arika Ishinami <[email protected]>
(cherry picked from commit 1761753)

* chore(deps): bump stefanzweifel/git-auto-commit-action from 4 to 7 (#236)

Bumps [stefanzweifel/git-auto-commit-action](https://github.com/stefanzweifel/git-auto-commit-action) from 4 to 7.
- [Release notes](https://github.com/stefanzweifel/git-auto-commit-action/releases)
- [Changelog](https://github.com/stefanzweifel/git-auto-commit-action/blob/master/CHANGELOG.md)
- [Commits](stefanzweifel/git-auto-commit-action@v4...v7)

---
updated-dependencies:
- dependency-name: stefanzweifel/git-auto-commit-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
(cherry picked from commit 107f2d2)

* Bump AutoMapper from 15.1.0 to 16.0.0 (#237)

---
updated-dependencies:
- dependency-name: AutoMapper
  dependency-version: 16.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
(cherry picked from commit 623b9fa)

* feat: optimize DTO generation and performance documentation (#235)

* Refactor GenerateDtoClasses method for improved readability and performance

* Add caching for pre-built expressions in SelectExprInfoNamed

* Refactor nullable access conversion to simplify default value handling

* Update performance documentation to clarify benchmarks and improve readability

* Update README to simplify performance and FAQ sections

* Fix nullable type handling in GetDefaultValueForType method

(cherry picked from commit 54005a1)

* formatted

(cherry picked from commit 11122cb)

* chore: update commit message format for csharpier workflow

(cherry picked from commit 735eb9f)

* playground: enable ScrollBeyondLastLine and update StickyScroll options in EditorPane and PreviewPane

(cherry picked from commit 9bc3057)

* Deduplicate DTO class definitions globally across all generated files (#240)

* Initial plan

* Fix duplicate ChildDto generation for same-shaped nested DTOs in Select expressions

Co-authored-by: arika0093 <[email protected]>

* Improve code comments based on review feedback

Co-authored-by: arika0093 <[email protected]>

* Fix duplicate DTO class definitions by deduplicating at generation point

Reverted changes to DtoProperty.cs and implemented deduplication in
GenerateSourceCodeSnippets.BuildDtoCodeSnippetsGroupedByNamespace instead.
This ensures DTOs with the same FullName (namespace + class name) are only
generated once, even when used across multiple SelectExpr calls.

Co-authored-by: arika0093 <[email protected]>

* Implement global DTO deduplication across all files

- Collect all DTOs from all SelectExpr groups
- Deduplicate globally by FullName before generation
- Generate all DTOs in a single shared GeneratedDtos.g.cs file
- Each expression group file now only contains expression methods
- This ensures DTOs are not duplicated even when used across different files

Co-authored-by: arika0093 <[email protected]>

* Refactor DTO generation based on code review feedback

- Moved global DTO deduplication logic to GenerateSourceCodeSnippets.BuildGlobalDtoCodeSnippet
- Separated SelectExprGroups.GenerateCode into two methods: GenerateCode and GenerateCodeWithoutDtos
- Made GenerateCommentHeaderPart and GenerateHeaderFlagsPart public for cross-namespace use
- Renamed test files to Issue239_* pattern for clarity
- Updated playground CodeGenerationService to use new global DTO deduplication
- Fixed null reference warning in playground service

Co-authored-by: arika0093 <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: arika0093 <[email protected]>
(cherry picked from commit 16b287e)

* refactor: DTO handling and improve code clarity (#216)

* refactor: improve code structure and add documentation for auto-generated DTO attribute

* refactor: rename ExportAll method to ExportAllConstantSnippets for clarity

* refactor: replace hardcoded DTO attributes with a dedicated method for better maintainability

* refactor: add EditorBrowsable attribute to internal DTO attributes for better visibility control

(cherry picked from commit ae2ba5f)

* fix

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: arika0093 <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: The code generated for nested SelectExpr is still insufficient

2 participants