dotnet / dotnet/efcore

Constructor calls (including with parameters) are translated as long as there are initializations

Open
#31,315 13 comments 0 reactions 0 assignees View on GitHub
area-query customer-reported needs-design
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

For #31279, I looked at our translation policy around constructors:

```c#
// FAILS (GOOD)
_ = ctx.Blogs
.Select(b => new Blog(1))
.Where(b => b.Name == "sdf")
.ToList();

// WORKS (GOOD)
_ = ctx.Blogs
.Select(b => new Blog { X = Y })
.Where(b => b.Name == "sdf")
.ToList();

// FAILS (OK, but somewhat inconsistent with the above - could just translate to an empty Blog etc.)
_ = ctx.Blogs
.Select(b => new Blog())
.Where(b => b.Name == "sdf")
.ToList();

// WORKS (PROBLEMATIC)
_ = ctx.Blogs
.Select(b => new Blog(1) { X = Y })
.Where(b => b.Name == "sdf")
.ToList();
```

It seems problematic to allow constructors with parameters when initializers are present. We obviously can't do anything with the arguments so they are silently ignored, although users may mistakenly think that they're being assigned to some property.

As a secondary thing, it's a bit odd to disallow `new Blog()` when we allow `new Blog { X = Y }`; after all in the latter case there may be other properties on Blog which are left uninitialized - so why not allow that for all properties with `new Blog()`. But it's probably not very useful as a query feature.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.