How does EF select a ctor for an entity with multiple ctors?
When an entity has multiple constructors, EF chooses one according to some undocumented logic.
Suppose an entity has a mix of:
- public parameterless constructor, and
- one or more parameterised constructors,
- of which some are private, protected, public, etc.
...then which constructor will EF choose?
The doc page only states this:
Currently, all constructor binding is by convention. Configuration of specific constructors to use is planned for a future release.
But the CURRENT selection logic is not described.
I understand that in a future release we will be able to specify which ctor to use, but until then, please document the current selection logic, because getting this to work in a large domain is extremely tedious trial-and-error.
Document Details
⚠ Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.
- ID: ecc7aedf-6301-7ec7-4f65-81749b1f54c8
- Version Independent ID: d0774ffa-c841-e6df-72de-d7f53c0d6f6f
- Content: Entity types with constructors - EF Core
- Content Source: entity-framework/core/modeling/constructors.md
- Product: entity-framework
- Technology: entity-framework-core
- GitHub Login: @ajcvickers
- Microsoft Alias: avickers
I just found this from ajcvickers:
Initial decision: for scalar properties, match zero by default (avoids breaking change) then fewest to most (avoids ignoring field mapping configuration)
Was that a design discussion, or is it the current selection process? And what about access modifiers?
If that is how it works, please consider adding it to that small purple note block I linked to above. Would help many people.
And until we get an API to deal with this issue, here is a workaround. However it isn't useful in an inheritance hierarchy (due to the static).
For anyone curious, this seems to best the documentation of this behaviour available at the moment:
Trying to find the constructor with the most service properties followed by the least scalar property parameters
https://github.com/dotnet/efcore/blob/master/src/EFCore/Metadata/Internal/ConstructorBindingFactory.cs#L121-124