Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lonix1 opened this issue Apr 12, 2023 · 3 comments
Open

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

lonix1 opened this issue Apr 12, 2023 · 3 comments

Comments

@lonix1
Copy link

lonix1 commented Apr 12, 2023

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
Copy link
Author

lonix1 commented Apr 12, 2023

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
Copy link
Author

lonix1 commented Apr 12, 2023

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

@ajcvickers ajcvickers added this to the Backlog milestone Apr 17, 2023
@ajcvickers ajcvickers self-assigned this Apr 17, 2023
@ajcvickers ajcvickers removed their assignment Aug 31, 2024
@alexanderchr
Copy link

alexanderchr commented Dec 16, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants