我正在使用EF 4.1,并且创建了一个正常的EF edmx文件。我从数据库生成它。实体框架无法使用正在创建的DbContext模型
当它生成后,我右键单击并选择添加代码生成项,生成新类,然后使用DbContext。我使用模板DbContext生成器。
一切工作正常。
然后我TRIE查询上下文:
using (var context = new PasDBEntities())
{
var client=context.ClientCompanies.SingleOrDefault(_=>_.ID==clientCompanyId);
if(client!=null)
我没有问题,创建上下文的新实例,但是当我尝试查询它的问题发生。我遇到了UnintentionalCodeFirstException。 并得到错误:
{"Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception."}
我不想先用代码,但我不知道我是否能够“开关”其关闭,或者问题出在哪里。
供参考,这是我的构造函数...
public partial class PasDBEntities : DbContext
{
public PasDBEntities()
: base("PasDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
...和连接字符串:
<connectionStrings>
<add name="PasDBEntities"
connectionString="metadata=res://*/PasDB.csdl|
res://*/PasDB.ssdl|
res://*/PasDB.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=localhost;
initial catalog=PasDB;
integrated security=True;
pooling=False;
multipleactiveresultsets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
是在(引用除外)的“执行应用程序** **的配置文件”此连接字符串,并不仅在配置文件一个图书馆项目? – Slauma
你是对的。我不知道我必须在单元测试项目中为连接字符串添加额外的配置文件才能使用EF。这解决了我的问题,添加了另一个app.config文件。 – Fore