2013-05-18 49 views
1

我新的實體框架代碼首先..哪些錯誤與下面的代碼..EF代碼優先table.add()方法總是返回表異常nullreference爲空

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 

我的數據庫上下文被命名爲作爲示例如下

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 

主臺總是ñ呃..表沒有創建....空引用異常顯示。請幫我看看這個..

回答

0

看起來問題在於你將MainTable定義爲一個字段,但DbContext類通過查找屬性來發揮它的魔力。嘗試將其更改爲:

Public Property MainTable As DbSet(Of MainDb) 

(一個自動實現的性質一樣,不夠好 - 你不需要自己進行初始化,班會爲你做它。)

希望這將做的伎倆!