-
Notifications
You must be signed in to change notification settings - Fork 3.2k
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
Decide on which constructor to call by convention #10852
Comments
Initial decision: for scalar properties, match zero by default (avoids breaking change) then fewest to most (avoids ignoring field mapping configuration) and change using fluent API/annotations when available. Also, file an issue to consider changing this in the next breaking release. |
Issue #10852 Now we pick the constructors with the most number of services, followed by the constructor with the least number of regular properties.
Issue #10852 Now we pick the constructors with the most number of services, followed by the constructor with the least number of regular properties.
It could also try to find a constructor by visibility, so that it first looks for a private constructor. So that a entity could be designed with a private constructor for use by EF, and a public constructor for use by developers for creating a new instance of the class. I have to work around this using a a public static method together with a private constructor. public class Blog
{
private HashSet<Post> _posts = null!;
// Private constructor for Entity Framework
private Blog(int blogId, string url)
{
BlogId = blogId;
Url = url;
}
public int BlogId { get; private set; }
public string Url { get; private set; }
public IReadOnlyCollection<Post> Posts => _posts.ToList().AsReadOnly();
// Static method to create an instance with _posts set to empty instead of null.
public static Blog Create(int blogId, string url)
{
var blog = new Blog(blogId, url);
blog._posts = new HashSet<Post>();
return blog;
}
} |
I'm facing a similar issue related to readonly-properties. I'm using EF Core 3. I'm trying to use readonly properties by taking advantage of constructors. Here's an example: public class Contact
{
public Contact() { }
public Contact(string name)
{
Name = name;
}
public string Name { get; }
} When loading Contacts from store, EF uses the parameterless constructor instead of the other one that takes the property values. Note: I've explicitly included the |
EF may be able to call several of the constructors defined on an entity type. By convention, we should always choose the one with the most number of services that can map--similar to D.I. However, when mapping scalar properties, we could:
Note that if only one constructor is defined, then EF will use it--this is just about the case when multiple are defined.
The text was updated successfully, but these errors were encountered: