为什么EF创建新数据库而不是使用现有数据库?

时间:2012-11-01 01:55:56

标签: entity-framework

我有一个填充了数据的现有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=&quot;data source=(local)\sqlexpress;initial catalog=Contacts;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" 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; }
    }

0 个答案:

没有答案