Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,15 @@ private void CollectTypes(Context context, Selection selection, TypeContainer pa
}

// Preferred path for mutable types.
var parameterlessConstructor = context.ParentType.GetConstructor(Type.EmptyTypes);
var parameterlessConstructor = context.ParentType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
binder: null,
Type.EmptyTypes,
modifiers: null);
if (parameterlessConstructor is not null)
{
var allWritable = assignmentList.All(a =>
a.Member is PropertyInfo { CanWrite: true, SetMethod.IsPublic: true });
a.Member is PropertyInfo { CanWrite: true });

if (allWritable)
{
Expand All @@ -266,7 +270,9 @@ private void CollectTypes(Context context, Selection selection, TypeContainer pa
}

// Fallback path for record-like types without a parameterless constructor.
var bestMatchingConstructor = context.ParentType.GetConstructors()
var bestMatchingConstructor = context.ParentType
.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(c => !IsRecordCopyConstructor(c, context.ParentType))
.Select(c => (Constructor: c, Parameters: c.GetParameters()))
.OrderBy(c => c.Parameters.Length)
.FirstOrDefault(c =>
Expand Down Expand Up @@ -305,8 +311,15 @@ private void CollectTypes(Context context, Selection selection, TypeContainer pa
return Expression.New(bestMatchingConstructor.Constructor, arguments);
}

throw new InvalidOperationException(
$"No writable properties or suitable constructor found for type '{context.ParentType.Name}'.");
// Real projection (member-init or a covering constructor) is now attempted first even
// for non-public construction surfaces (a non-public parameterless constructor with
// non-public setters, or a non-public covering constructor), so this reuse is only
// reached for EF DI/proxy entities and for types that can neither be constructed nor
// partially bound. We reuse the source instance as a last resort (the same expression
// the reuse-first branch returns). Projection only optimizes data fetching; the
// GraphQL execution layer still shapes the response to the selection set, so reuse
// is always valid (it may fetch more columns than strictly required).
return context.Parent;
}

private void CollectSelection(
Expand Down
209 changes: 209 additions & 0 deletions src/HotChocolate/Data/test/Data.Tests/ResolveWithProjectionTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Linq.Expressions;
using HotChocolate.Execution;
using HotChocolate.Execution.Processing;
using HotChocolate.Types;
Expand Down Expand Up @@ -98,13 +99,221 @@ public async Task ResolveWith_Should_Project_Member_When_AsSelector_Is_Used_On_P
""");
}

[Fact]
public async Task AsSelector_Should_Project_When_Type_Has_Only_Private_Constructors()
{
// arrange
var executor = await new ServiceCollection()
.AddGraphQL()
.AddQueryType<PrivateCtorQuery>()
.BuildRequestExecutorAsync(cancellationToken: TestContext.Current.CancellationToken);

// act
var result = await executor.ExecuteAsync(
"""
{
items {
id
name
}
}
""",
TestContext.Current.CancellationToken);

// assert
result.MatchInlineSnapshot(
"""
{
"data": {
"items": [
{
"id": 1,
"name": "Foo"
}
]
}
}
""");
}

[Fact]
public async Task AsSelector_Should_UseMemberInit_When_Type_Has_Only_NonPublic_ParameterlessConstructor()
{
// arrange
var captured = new List<Expression<Func<PrivateCtorEntity, PrivateCtorEntity>>>();
var executor = await new ServiceCollection()
.AddSingleton(captured)
.AddGraphQL()
.AddQueryType<PrivateCtorCaptureQuery>()
.BuildRequestExecutorAsync(cancellationToken: TestContext.Current.CancellationToken);

// act
await executor.ExecuteAsync(
"""
{
items {
id
name
}
}
""",
TestContext.Current.CancellationToken);

// assert
var selector = Assert.Single(captured);
Assert.IsType<MemberInitExpression>(selector.Body);
}

[Fact]
public async Task AsSelector_Should_UseConstructor_When_Type_Has_Only_NonPublic_CoveringConstructor()
{
// arrange
var captured = new List<Expression<Func<CoveringCtorEntity, CoveringCtorEntity>>>();
var executor = await new ServiceCollection()
.AddSingleton(captured)
.AddGraphQL()
.AddQueryType<CoveringCtorCaptureQuery>()
.BuildRequestExecutorAsync(cancellationToken: TestContext.Current.CancellationToken);

// act
await executor.ExecuteAsync(
"""
{
items {
id
name
}
}
""",
TestContext.Current.CancellationToken);

// assert
var selector = Assert.Single(captured);
var newExpression = Assert.IsType<NewExpression>(selector.Body);
Assert.NotNull(newExpression.Constructor);
Assert.False(newExpression.Constructor.IsPublic);
}

[Fact]
public async Task AsSelector_Should_ExecuteInMemory_When_Type_Has_Only_NonPublic_CoveringConstructor()
{
// arrange
var executor = await new ServiceCollection()
.AddGraphQL()
.AddQueryType<CoveringCtorQuery>()
.BuildRequestExecutorAsync(cancellationToken: TestContext.Current.CancellationToken);

// act
var result = await executor.ExecuteAsync(
"""
{
items {
id
name
}
}
""",
TestContext.Current.CancellationToken);

// assert
result.MatchInlineSnapshot(
"""
{
"data": {
"items": [
{
"id": 1,
"name": "Foo"
}
]
}
}
""");
}

public class Query
{
[UseProjection]
public IQueryable<Tenant> GetTenants()
=> CreateTenants().AsQueryable();
}

public class PrivateCtorQuery
{
public IQueryable<PrivateCtorEntity> GetItems(ISelection selection)
=>
new[] { PrivateCtorEntity.Create(1, "Foo") }
.AsQueryable()
.Select(selection.AsSelector<PrivateCtorEntity>());
}

public class PrivateCtorEntity
{
private PrivateCtorEntity()
{
}

private PrivateCtorEntity(int id, string name)
{
Id = id;
Name = name;
}

public int Id { get; private set; }

public string Name { get; private set; } = default!;

public static PrivateCtorEntity Create(int id, string name)
=> new(id, name);
}

public class PrivateCtorCaptureQuery
{
public IQueryable<PrivateCtorEntity> GetItems(
ISelection selection,
[Service] List<Expression<Func<PrivateCtorEntity, PrivateCtorEntity>>> captured)
{
captured.Add(selection.AsSelector<PrivateCtorEntity>());
return new[] { PrivateCtorEntity.Create(1, "Foo") }.AsQueryable();
}
}

public class CoveringCtorQuery
{
public IQueryable<CoveringCtorEntity> GetItems(ISelection selection)
=>
new[] { CoveringCtorEntity.Create(1, "Foo") }
.AsQueryable()
.Select(selection.AsSelector<CoveringCtorEntity>());
}

public class CoveringCtorCaptureQuery
{
public IQueryable<CoveringCtorEntity> GetItems(
ISelection selection,
[Service] List<Expression<Func<CoveringCtorEntity, CoveringCtorEntity>>> captured)
{
captured.Add(selection.AsSelector<CoveringCtorEntity>());
return new[] { CoveringCtorEntity.Create(1, "Foo") }.AsQueryable();
}
}

public class CoveringCtorEntity
{
private CoveringCtorEntity(int id, string name)
{
Id = id;
Name = name;
}

public int Id { get; private set; }

public string Name { get; private set; } = default!;

public static CoveringCtorEntity Create(int id, string name)
=> new(id, name);
}

public class AsSelectorQuery
{
public IQueryable<Tenant> GetTenants(ISelection selection)
Expand Down
Loading