George Mauer
George Mauer

Reputation: 122052

Why can't EF assign my child collection when the constructor is private?

I have an entity that looks like this

public class SlideSet {
    public SlideSet(string name) : this() {
       Name = name
    }
    public SlideSet() {
        Params = new HashSet<SlideSetParameter>();
    }

    [Required]
    public string Name { get; set; }
    public virtual ICollection<SlideSetParameter> Params { get; set; } 
}

I just noticed that I'm not actually using the second constructor ever and that it actually makes no sense in my domain so I made it private. All of a sudden the Params array stopped loading and always gives me a length of 0. What's going on? In order for it to load I need my constructor to be at least protected. Why?

Upvotes: 1

Views: 195

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109079

One of the conditions for EF to be able to create proxies (necessary for lazy loading) is

The class must have a public or protected parameter-less constructor.

From here (an old link, but this part still applies)

The proxy is a derived type and it must be able to call the parameterless constructor of the base type.

Upvotes: 5

krillgar
krillgar

Reputation: 12805

You need to have your default constructor set to public, as that is what Entity Framework is going to use to create your objects. Having it as private, it is unable to initialize the Params property, and therefor is trying to add any SlideSetParameters to a null object.

Upvotes: 0

Related Questions