0

我正在尝试使用 Database.SetInitializer 初始化数据库,但是当我的初始化程序类确实从 DBContext 继承时,我得到一个“类型参数不继承自或实现约束类型“System.Data.Entity.DBContext”错误。有任何想法吗?顺便说一句,我是 Code First EF 的新手!

上下文类:

Imports System.Data.Entity
Imports System.Collections.Generic
Imports System.Data.Entity.Infrastructure
Imports System.Configuration

Public Class PropertyManagementContext
    Inherits DbContext

#Region "Constructor"
    Public Sub New()
        MyBase.New("Data Source=WSBS2K3SQL;Initial Catalog=AQUARIUS_TEST;Persist    Security Info=True;User ID=SomeUser;Password=SomePassword;")

    End Sub

#End Region

#Region "Tables"
    Public Complexes As DbSet(Of Complex)
    Public Buildings As DbSet(Of Building)
    Public Units As DbSet(Of Unit)
    Public Tenants As DbSet(Of Tenant)
#End Region

Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
    MyBase.OnModelCreating(modelBuilder)

    'Set the Primary Keys
    modelBuilder.Entity(Of Complex).HasKey(Function(c) c.ComplexId)
    modelBuilder.Entity(Of Building).HasKey(Function(b) b.BuildingId).HasKey(Function(b) b.ComplexId)
    modelBuilder.Entity(Of Unit).HasKey(Function(u) u.UnitId).HasKey(Function(u) u.BuildingId)
    modelBuilder.Entity(Of Tenant).HasKey(Function(t) t.TenantId)

    'Set Complex Primary Key to Identity(MS SQL Auto-Increment)
    modelBuilder.Entity(Of Complex).Property(Function(c) c.ComplexId) _
    .HasDatabaseGeneratedOption(ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)

End Sub

End Class

初始化类:

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Data.Entity

Public Class PropertyManagementInitializer
    Inherits DropCreateDatabaseAlways(Of PropertyManagementContext)

Protected Overrides Sub Seed(context As PropertyManagementContext)
    MyBase.Seed(context)

    Dim complex As New Complex With {
        .Name = "SomeComplex",
        .City = "SomeCity",
        .Address = "SomeStreet",
        .PostalCode = "R2R2R2",
        .Type = "1"
    }
    context.Complexes.Add(complex)

    context.SaveChanges()

End Sub

End Class

调用 Database.SetInitializer() 并给出错误的主窗体:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try    
        Database.SetInitializer(Of PropertyManagementContext)(New PropertyManagementInitializer)

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

End Sub
4

1 回答 1

3

我以前见过这种情况,对我来说,Visual Studio 似乎以一种有趣的方式来修复我删除“继承 DbContext”运行构建,然后重新添加“继承 DbContext”并再次构建解决方案,Visual Studio 不再抱怨。

于 2012-10-25T04:36:58.090 回答