dotnet / dotnet/EntityFramework.Docs

"Entity types with constructors" documentation doesn't explain how the framework prioritizes constructors for instantiation.

Open
#3,636 2 comments 1 reaction 0 assignees View on GitHub
area-model-building
Dominant language
Mermaid
Stars
1.7k
Forks
2k
Avg merge
7d 23h
Merged PRs (30d)
16

Description

"Entity types with constructors" documentation doesn't explain how the framework prioritizes constructors for instantiation.

The ambiguous text in question:

> When EF Core creates instances of these types, such as for the results of a query, it will first call the default parameterless constructor and then set each property to the value from the database. However, if EF Core finds a parameterized constructor with parameter names and types that match those of mapped properties, then it will instead call the parameterized constructor with values for those properties and will not set each property explicitly.

Does the framework look for the constructor that has the greatest number of parameters matching properties?
Is it possible to define which constructor for a given entity should be used? Or to set the global method of choosing?

In my case, I've got a private default constructor I always leave for EF Core.
I have another internal constructor my domain services use to create the entity, and that constructor can have some heavy validation or other type of logic inside itself.
If I create another private constructor that accepts parameters for all the properties, will that one be prioritized over the one mentioned above?

What if I already have a constructor that accepts parameters for all properties and does some logic I wouldn't want to run on EFCore's entity instantiation?
How could I solve that, given that I can't create two constructors with the same parameter signature?

EDIT: I've tested it out on EFCore 6.0.1. The framework prioritizes the constructor with minimal parameter count (including 0) where all parameters correspond to a property.
If this was made clear in the documentation I wouldn't have had to waste time on testing it out!

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.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](https://docs.microsoft.com/en-us/ef/core/modeling/constructors)
* Content Source: [entity-framework/core/modeling/constructors.md](https://github.com/dotnet/EntityFramework.Docs/blob/main/entity-framework/core/modeling/constructors.md)
* Product: **entity-framework**
* Technology: **entity-framework-core**
* GitHub Login: @ajcvickers
* Microsoft Alias: **avickers**

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.