我是Entity框架代码的新手。以下代码出错了。
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
My Db Context命名为样本,如下所示
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
Main表始终为null ..表未创建....显示空引用异常。请帮帮我...
答案 0 :(得分:0)
看起来问题在于您将MainTable
定义为字段,但DbContext
类通过查找属性来发挥其神奇作用。尝试将其更改为:
Public Property MainTable As DbSet(Of MainDb)
(像这样的自动实现的属性足够好 - 你不需要自己初始化它,类会为你做。)
希望这会有所作为!