我正在尝试使用Database.SetInitializer初始化数据库,但是我得到一个'Type参数不继承或实现约束类型'System.Data.Entity.DBContext'当我的初始化器类继承自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
答案 0 :(得分:3)
我以前见过这个,对我而言似乎Visual Studio以一种有趣的方式修复我删除了“继承DbContext”运行构建然后重新添加“继承DbContext”并再次构建解决方案,Visual Studio不再抱怨