我有一个现有的 SQL Server Express 数据库,其中填充了数据。
我创建了一个围绕 EF 5 构建的新 VS 解决方案。我从现有数据库生成了 EDMX,并验证了app.config
指向数据库的连接字符串.\SQLEXPRESS
。
我为我的域对象创建了一个项目。
我添加了一个DbContext
生成器。域对象也被生成。
一切都建立起来,控制台应用程序运行。
然而,问题是创建了一个新数据库而不是使用现有数据库。
为什么 EF 创建一个新的空数据库而不是使用我指定的现有数据库?我该如何解决?
这是DbContext
课程:
public partial class ContactsEntities : DbContext
{
public ContactsEntities()
: base("name=ContactsEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Address> Addresses { get; set; }
public DbSet<AddressType> AddressTypes { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
}
和整个app.config
:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ContactsEntities" connectionString="metadata=res://*/PeopleModel.csdl|res://*/PeopleModel.ssdl|res://*/PeopleModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(local)\sqlexpress;initial catalog=Contacts;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
这是使用 T4Scaffolding 搭建的 PeopleContext:
public class PeopleContext : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, add the following
// code to the Application_Start method in your Global.asax file.
// Note: this will destroy and re-create your database with every model change.
//
// System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<DataLayer.Models.PeopleContext>());
public DbSet<Domain.Person> People { get; set; }
}