c# - 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.
解决方案
查看数据库上下文的构造函数。例如,
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());
}
最后两行将确保创建数据库及其表,如果不存在并且完全匹配存在的内容。
推荐阅读
- javascript - 在 javascript/jquery 中的页面重新定位和浏览器/选项卡关闭上显示自定义弹出窗口
- javascript - 如何从 JSON 数组对象响应创建嵌套数据表
- javascript - 我如何从 Web 元素中获取文本并在控制台中打印(例如)
- dart - NoSuchMethodError:在 null 上调用了 getter 'value'。:为颤振中的下拉按钮填充下拉项列表
- node.js - NodeJS 未成功安装在用户数据内的 AWS EC2 中
- jquery - 如何根据选择的另一个选择选项(数组)更改选择选项?
- sql - 为什么即使我添加了 jdbcType,插入也会失败并显示错误代码 17004?
- sql - 同一列的两个索引并更改顺序
- maven - 缺少 Maven 依赖项
- charts - 图表js:根据数据生成动态标签