I am trying to initialize a database using Database.SetInitializer but I am getting a ‘Type argument does not inherit from or implement the constraint type ‘System.Data.Entity.DBContext’ Error when my initializer class DOES inherit from DBContext. Any ideas? I’m new to Code First EF by the way!
Context Class:
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
Initializer 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
Main Form where Database.SetInitializer() is called and giving the error:
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
I have seen this before and for me it seemed that Visual Studio was in a funny way to fix I removed “Inherits DbContext” run a build and then re added “Inherits DbContext” and built solution again, Visual Studio no longer complained.