Search code examples
c#entity-frameworkcode-first

Entity Framework Exception has been thrown by the target of an invocation


I'm trying to make a really simple entity Framework Code First project, but can't manage to solve a "Exception has been thrown by the target of an invocation." when I'm trying to retrieve data from my database.

I have a unique class :

public class TestStylo
{
    [Key]
    public int TestStyloID { get; set; }
    StyloType styloType { get; set; }
    public string name;

    public TestStylo(StyloType styloType, string name)
    {
        this.styloType = styloType;
        this.name = name;
    }
    public StyloType getTypeStylo{
        get { return styloType; }
    }


}
public enum StyloType
{
    pen,
    wood,
    gold
}

my Model is :

public class Model1 : DbContext
{
     public Model1()
        : base("name=Model1")
    {
    }

    public  DbSet<TestStylo> MyStylos { get; set; }
}

And my App.Config is :

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="Model1" connectionString="data source=(LocalDb)\v11.0;initial catalog=TestCodeFirst.Model1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

My connectionString is working, I can manually open and see my database and it's content. When I try to add content to my database I use :

using (Model1 db = new Model1())
            {
                TestStylo stylo = new TestStylo(StyloType.pen,"numberOne");
                db.MyStylos.Add(stylo);
                db.SaveChanges();
            }

and it works for the most part (it only insert the ID .. but I'll see that later)

But when I try to retrieve with :

private void button2_Click(object sender, EventArgs e)
        {
            using (Model1 db = new Model1())
            {
                var stylos = from order in db.MyStylos
                              select order;

                ...
            }
        }

I'm getting an "Exception has been thrown by the target of an invocation." with an Inner-Exception {"The class 'TestCodeFirst.TestStylo' has no parameterless constructor."}.

Why am I getting such an error ?


Solution

  • The actual error is presented in the inner exception:

    The class 'TestCodeFirst.TestStylo' has no parameterless constructor.

    All entities should have a parameterless constructor in order to be used by Entity Framework.

    You can simply add this constructor to your entity:

    public class TestStylo
    {
        [Key]
        public int TestStyloID { get; set; }
        StyloType styloType { get; set; }
        public string name;
    
        public TestStylo(StyloType styloType, string name)
        {
            this.styloType = styloType;
            this.name = name;
        }
        public StyloType getTypeStylo{
            get { return styloType; }
        }
    
        // Add this:
        public TestStylo()
        {
    
        }
    }
    

    This constructor can actually be internal or private if you do not want to expose the public constructor.