首页 > 解决方案 > Why does Entity Framework try to build an already existing database?

问题描述

In both my Services and WebSite Web.config file, I have the following connection string:

<connectionStrings>
  <add name="MyDBConnect" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=MyDB;User Id=tester;Password=abc123*123;" providerName="System.Data.SqlClient" />
</connectionStrings>

I manually ran my database build script and have confirmed in the SSMS UI: (LocalDB)\MSSQLLocalDB (SQL Server 13.0.40001 - 8Protons) > Databases > MyDB

While running the project and going to the login screen, an exception is thrown at:

var entity = GetAll().Include(p => p.Role).FirstOrDefault(p => p.Email == userName && p.Password == encryptedPassword && p.IsActive);

with the following message

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code Additional information: CREATE TABLE permission denied in database 'MyDB'.

Why is the solution trying to CREATE a table when it already exists? So I went to the table is SSMS and elevated this user's permissions to create a table. The error that now gets thrown is:

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code Additional information: There is already an object named 'MyTable' in the database.

For context, this is after I've cloned someone's EF solution, built it, and am attempting to sign in to a log-in page that the solution is running. So this is a fresh solution on my local machine.

标签: c#sqlentity-frameworkmigrationssms

解决方案


查看数据库上下文的构造函数。例如,

public MyDBContext(string nameOrConnectionString)
    : base(nameOrConnectionString)
{
    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;
    this.Database.CommandTimeout = 60;

    IDatabaseInitializerCreator creator = new DatabaseInitializerCreator();
    Database.SetInitializer(creator.Create());
}

最后两行将确保创建数据库及其表,如果不存在并且完全匹配存在的内容。


推荐阅读