【发布时间】:2012-08-13 19:16:00
【问题描述】:
我是一个做过一些教程的 ASP MVC 3 新手。现在我正在尝试建立一个网站。 microsoft 网站上的所有教程都强调代码优先方法:您使用代码定义模型,然后创建数据上下文,然后实体框架根据您的代码创建/管理数据库。
我设置了一个Employees 类和一个继承自DbContext 的DataBaseContext 类。我向 Web.config 连接字符串添加了一个连接字符串,该连接字符串成功地将 DataBaseContext 链接到 SQL 服务器上已经存在的空数据库。 EDIT= 这就是问题所在。请参阅下面的答案
但是当我尝试运行通过脚手架创建的员工控制器时,我得到了这个错误
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
这是员工的代码:
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
这是数据库上下文的代码:
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
我错过了什么?
【问题讨论】:
-
您能否发布您为员工提供的模型类和 dbcontext 类。听起来您正在尝试使用实体框架代码优先,对吗?
-
@davidisawesome 我发布了附加代码
-
我认为您不需要 app_start 中的任何内容。让我看一下,我会试着弄清楚。这是一个全新的项目,还是你已经搞砸的东西?
-
全新项目。这可能是 sql server 权限或其他问题。我收到了一个 createTable not allowed 错误,但设法修复了那个错误。
-
使用 localdb 作为连接字符串还是您设置的单独字符串?