【发布时间】:2016-10-08 15:42:49
【问题描述】:
我正在尝试制作一个非常简单的实体 Framework Code First 项目,但无法解决“调用目标已引发异常”。当我试图从我的数据库中检索数据时。
我有一个独特的课程:
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
}
我的模特是:
public class Model1 : DbContext
{
public Model1()
: base("name=Model1")
{
}
public DbSet<TestStylo> MyStylos { get; set; }
}
而我的 App.Config 是:
<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>
我的 connectionString 正在工作,我可以手动打开并查看我的数据库及其内容。 当我尝试向我的数据库添加内容时,我使用:
using (Model1 db = new Model1())
{
TestStylo stylo = new TestStylo(StyloType.pen,"numberOne");
db.MyStylos.Add(stylo);
db.SaveChanges();
}
它在大多数情况下都有效(它只插入 ID .. 但我稍后会看到)
但是当我尝试检索时:
private void button2_Click(object sender, EventArgs e)
{
using (Model1 db = new Model1())
{
var stylos = from order in db.MyStylos
select order;
...
}
}
我收到一个带有内部异常 {"The class 'TestCodeFirst.TestStylo' has no parameterless constructor."} 的 "Exception has been thrown by the target of an invocation."。
为什么会出现这样的错误?
【问题讨论】:
标签: c# entity-framework code-first