Reputation: 60556
I have been working with EFCodeFirst (EFCTP 5) for some weeks now, without any problems.
But now I am getting an exception when adding an entity to a collection.
I have a User
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
}
and a DbContext
public class Foo : DbContext
{
public DbSet<User> Users { get; set; }
}
now I just want to add user
to the DbSet
.
Foo f = new Foo();
User us = new User()
{
FirstName = "FooName"
};
f.User.Add(us); //The exception is thrown on this line
the Exception message is
"System.MissingMethodException:No parameterless constructor defined for this object"
Upvotes: 1
Views: 1239
Reputation: 11
This is a combination of a design flaw in EF and a problem with reflection.
Often it reports:
MissingMethodException: No parameterless constructor defined for this object.
When what it means is "I called the constructor and it threw an exception".
For instance, if the connection string is incorrect in a config file - it will often fail to construct the EF Context object; throwing the error above. All SQL exceptions concerning the malformed connection string seem to get eaten by EF or the reflection code.
I suspect something similar is happening here.
Enable catching first chance exceptions in visual studio. See exceptions under the debug menu, check the box for "thrown" "common language runtime exceptions"
This should reveal what is failing in the constructor.
Upvotes: 1
Reputation: 675
This may or may not work for you because my situation is different in that I'm using the POCO Generation Template for EF4.
I had an Entity which had readonly
properties that I didn't want to be created without those property values being set, so I created a parameterized constructor. One of the properties I needed to set was a many-1 relationship from the new Entity to another that was passed in. Because of the Proxy fixup code, whenever that Entity property was set in the constructor, I received an InvalidOperationException
stating there was no parameterless Constructor for my Entity.
Solution: created a protected
parameterless constructor which had an empty body. I also needed to do this for its subclass.
Upvotes: 0