Reputation: 5743
I have a model with a parameterized constructor in EF core project:
public record Position {
public string AccountId {get;}
public string ContractId {get;}
// throws exception without private init
public DateTime CreationDate {get; private init;}
public Position(string accountId, string contractId, DateTime creationDate) {
...
}
}
For some reason EF core does not pick up creationDate
property in the constructor. If I remove the private init
method, it throws the exception:
No suitable constructor was found for entity type 'Position'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'creationDate' in 'Position(string accountId, string contractId, DateTime creationDate)'.
I cannot figure out the source of the issue, since their example suggests it is possible: https://learn.microsoft.com/en-us/ef/core/modeling/constructors
Upvotes: 0
Views: 1882
Reputation: 205759
As the document states, it is possible to use the constructor if the arguments can be mapped to properties.
The problem is that by default the CreationDate
is not considered to be a model property. Because as mentioned in the Included and excluded properties section:
By convention, all public properties with a getter and a setter will be included in the model.
All your properties are get only, so they are not automatically included in the model, so you have to do that manually, e.g.
modelBuilder.Entity<Position>().Property(e => e.CreationDate);
If you are wondering why CreationDate
and not the other two, it's because most likely you already included them in the model by configuring them to compose the PK of the entity, i.e. something like this
modelBuilder.Entity<Position>().HasKey(e => new { e.AccountId, e.ContractId });
also includes AccountId
and ContractId
w/o explicit .Property
call.
In general it's not a good idea to use get only properties in EF data models. Neither C#9 record types. Simple classes with get/set properties, this is supposed to be data model, not business/domain model with applied OO principles like encapsulation etc.
Upvotes: 4