Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 未使用代码优先方法创建数据库_Asp.net Mvc_Vb.net - Fatal编程技术网

Asp.net mvc 未使用代码优先方法创建数据库

Asp.net mvc 未使用代码优先方法创建数据库,asp.net-mvc,vb.net,Asp.net Mvc,Vb.net,我见过一些类似的问题,但似乎没有人回答我的问题-最常见的回答似乎是“延迟加载-当您尝试访问数据库/表时,将创建它们”。在这种情况下,我是: Dim students As List(Of Student) = db.Students.ToList 由于students表为空/null,上述操作引发了一个错误 以下是我(非常简单)的学校背景: Imports System.Data.Entity Public Class SchoolContext Inherits DbCon

我见过一些类似的问题,但似乎没有人回答我的问题-最常见的回答似乎是“延迟加载-当您尝试访问数据库/表时,将创建它们”。在这种情况下,我是:

        Dim students As List(Of Student) = db.Students.ToList
由于students表为空/null,上述操作引发了一个错误

以下是我(非常简单)的学校背景:

Imports System.Data.Entity

Public Class SchoolContext
Inherits DbContext

Public Students As DbSet(Of Student)

End Class
这是我的学校初始化器课程:

Imports System.Data.Entity

Public Class SchoolInitializer
Inherits DropCreateDatabaseAlways(Of SchoolContext)


Protected Overrides Sub Seed(context As SchoolContext)
    Dim students As List(Of Student) = New List(Of Student) From {
    New Student("Jessica", "Jones"),
    New Student("Chuck", "Norris"),
    New Student("Rambo", "John")
    }

    For Each student In students
        context.Students.Add(student)
    Next

    context.SaveChanges()

End Sub
End Class
和web.config中的我的连接字符串:

<add name="SchoolContext" connectionString="Data Source=    (LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\school.mdf;Initial Catalog=aspnet-WebApplication1-20160205092922;Integrated Security=True" providerName="System.Data.SqlClient" />
似乎没有在我的AppData文件夹中创建数据库,据我所知,一切都设置好了,好吗?有什么建议吗

我将遵循以下教程:


谢谢

所以我想出了这个办法,以防有人遇到类似的问题。我用的是VB,所以我想在c#的翻译中有些东西会丢失

这实际上有一些问题。第一个是StudentContext类需要表的属性,而不是全局变量:

'NOT Public Students As DbSet(Of Student)
Public Property Students() As DbSet(Of Student)
在这之后,错误更容易被发现。第二个错误是由于我的学生模型上没有密钥,因此我添加了以下内容:

<Key()>
Public Property _StudentID As Integer

公共属性\u StudentID为整数
属性和全局变量。接下来,由于某种原因,它没有连接到数据库,所以我不得不下载并安装localDB

最后,它抱怨我没有无参数构造函数。因此,我必须在我的学生模型中添加一个空构造函数


最后-一切正常(耶)

我应该在控制器中提到,我得到的数据库上下文如下:Dim db As SchoolContext=新建SchoolContext Dim students As List(Of Student)=db.students.ToList
<Key()>
Public Property _StudentID As Integer