我是一个ASP MVC 3 noobie谁做了一些教程.现在我正在尝试建立一个网站.微软网站上的所有教程都强调代码优先方法:用代码定义模型,然后创建datacontext,然后实体框架根据代码创建/管理数据库.
我设置了一个Employees类和一个继承自DbContext的DataBaseContext类.我在Web.config连接字符串中添加了一个连接字符串,该字符串成功地将DataBaseContext链接到SQL Server上已存在的空DB.编辑=那就是问题所在.请参阅下面的答案
但是当我尝试运行通过脚手架创建的Employees控制器时,我收到此错误
Invalid object name 'dbo.Employees'.
Description: An unhandled exception occurred during the execution of...
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Employees'.
我按照这篇文章SqlException (0x80131904): Invalid object name ‘dbo.Categories’意识到如果我在数据库上创建一个雇员表,这个重复消失就会消失(我得到一个新的消息称列名无效).
但我认为MVC 3的重点在于框架将根据代码为您创建数据库.
也许我需要在Global.asax Application_start()中使用一行代码来创建数据库?这是我的application_start方法:
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterGlobalFilters(GlobalFilters.Filters)
RegisterRoutes(RouteTable.Routes)
End Sub
以下是Employee的代码:
Public Class Employee
Property EmployeeID As Integer
Property First As String
Property Last As String
Property StartDate As DateTime
Property VacationHours As Integer
Property DateOfBirth As DateTime 'in case two employees have the same name
End Class
以下是DB上下文的代码:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
我错过了什么?
最佳答案 默认情况下,EF使用DropCreateDatabaseIfModelChanges< TContext>数据库初始化器.相应于
MSDN:
An implementation of
IDatabaseInitializer<TContext>
that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created. This is achieved by writing a hash of the store model to the database when it is created and then comparing that hash with one generated from the current model.
由于数据库是手动创建的,因此EF无法找到散列并决定不执行任何进一步的初始化逻辑.