1

我首先是实体框架代码的新手..以下代码有什么问题..

Sub Main()
        Dim _Context As New Sample()
        _Context.Database.Initialize(True)
        Dim dbHead
        dbHead = New MainDb("Hai", "Bye")
        _Context.MainTable.Add(dbHead)
        _Context.SaveChanges()


End Sub

我的 Db 上下文被命名为示例,如下所示

Public Class Sample
    Inherits DbContext

    Public MainTable As DbSet(Of MainDb)

    Public Sub New()

    End Sub

    Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
        System.Data.Entity.Database.SetInitializer(New MyDbContextIntializer())
        MyBase.OnModelCreating(modelBuilder)
    End Sub

    Public Class MyDbContextIntializer
        Inherits DropCreateDatabaseIfModelChanges(Of Sample)

        Protected Overrides Sub Seed(context As Sample)
            MyBase.Seed(context)
        End Sub
    End Class
End Class

这是主要的缩进类

Imports System.ComponentModel.DataAnnotations.Schema
Imports System.ComponentModel.DataAnnotations

<Table("MainDb")>
Public Class MainDb

    Private _Name As String
    <Key()>
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _Class As String
    Public Property ClassName() As String
        Get
            Return _Class
        End Get
        Set(ByVal value As String)
            _Class = value
        End Set
    End Property

    Public Sub New(ByVal Name As String, ByVal CN As String)
        ClassName = CN
        Me.Name = Name
    End Sub

End Class

主表始终为空.. 表未创建.. 显示空引用异常。请帮我解决这个问题..

4

1 回答 1

0

看起来问题在于您将其定义MainTable为一个字段,但是DbContext该类通过查找属性来发挥其魔力。尝试将其更改为:

Public Property MainTable As DbSet(Of MainDb)

(像这样的自动实现的属性就足够了——你不需要自己初始化它,类会为你做。)

希望这会成功!

于 2013-05-18T04:25:31.467 回答