Value cannot be null. Parameter name: constructor

Using Entity Framework I occasionally get the following error when reading from the database - `exceptionMessage=Value cannot be null. Parameter name: constructor`

My Person class looked like this -

 1    public class Person
 2    {
 3        public Person(string firstname, string lastname)
 4        {
 5             Firstname = firstname;
 6             Lastname = lastname;
 7        }
 8
 9        public Guid PersonId { get; set; } 
10        public string Firstname { get; set; } 
11        public string Lastname { get; set; } 
12        public DateTime SomeDate { get; set; }
13     }

There is no way for Entity Framework to know how to instantiate this object because there is no empty constructor.

If you are following some of the principles of domain driven design you may not want a public empty constructor, no problem, make it private.

 1    public class Person
 2    {
 3        private Person(){} // Entity Framework queries will work now
 4
 5        public Person(string firstname, string lastname)
 6        {
 7             Firstname = firstname;
 8             Lastname = lastname;
 9        }
10
11        public Guid PersonId { get; set; } 
12        public string Firstname { get; set; } 
13        public string Lastname { get; set; } 
14        public DateTime SomeDate { get; set; }
15     }
comments powered by Disqus

Related