Code First总是希望在部署到另一台PC时创建新的数据库

本文关键字:PC 一台 创建 数据库 First 希望 部署 Code | 更新日期: 2023-09-27 18:11:54

我有一个win-form应用程序,使用CodeFirst来处理数据。
在从我的模型中创建数据库之后,我从另一个数据库中导入了记录。
它在我的PC上工作得很好,但当我将我的应用程序部署到另一台PC时,codefirst尝试创建新数据库并抛出此错误:

System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> 
System.Data.SqlClient.SqlException: Cannot create file 
'E:'New folder (2)'Release'MyDB_log.ldf' because it already exists.
Change the file path or the file name, and retry the operation.
Could not open new database 'MyDB'. CREATE DATABASE is aborted.
Cannot attach the file 'E:'New folder (2)'Release'MyDB.mdf' as database 'MyDB'.

连接字符串:

  <connectionStrings>
    <add name="AppDbContext"
    connectionString="Server=.'sqlexpress;AttachDbFilename=|DataDirectory|'MyDB.mdf;Database=MyDB;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
  </connectionStrings> 

AppDbContext:

public class AppDbContext :DbContext 
{
    static AppDbContext() {
         Database.SetInitializer<AppDbContext>(null);
    }
    public DbSet<Stock> Stocks { get; set; }
    public DbSet<Report> Reports { get; set; }

}
迁移类:

internal sealed class Configuration : DbMigrationsConfiguration<Sita_Election.DAL.AppDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        ContextKey = "Sita_Election.DAL.AppDbContext";
        AutomaticMigrationDataLossAllowed = false;
    }
    protected override void Seed(Sita_Election.DAL.AppDbContext context)
    {
    }
}

所以我想使用现有的数据库是创建在开发与代码优先,我怎么能做到这一点?

Code First总是希望在部署到另一台PC时创建新的数据库

每个应用程序有一个数据库的理由吗?

如果可能的话,我建议使用SQL数据库。

谢谢,

菲尔

您的连接字符串正在使用可信连接,因此您的IIS用户将需要访问该文件,或者您可以切换到sql登录。http://th2tran.blogspot.com/2009/06/underlying-provider-failed-on-open.html