EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

How does EF select a ctor for an entity with multiple ctors?

Open lonix1 opened this issue 2 years ago • 3 comments

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.

lonix1 avatar Apr 12 '23 03:04 lonix1

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.

lonix1 avatar Apr 12 '23 03:04 lonix1

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).

lonix1 avatar Apr 12 '23 03:04 lonix1

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

alexanderchr avatar Dec 16 '24 17:12 alexanderchr