Skip to content

Instantly share code, notes, and snippets.

@billgeek
Last active February 22, 2018 16:51
Show Gist options
  • Save billgeek/22873ceff4b9fe59b0a7277f0f7fe86b to your computer and use it in GitHub Desktop.
Save billgeek/22873ceff4b9fe59b0a7277f0f7fe86b to your computer and use it in GitHub Desktop.
Creating Entity Framework 6 Fluent API Models using Reflection (VB.NET)

Using Reflection and Fluent API to create EF6 Models (VB.NET)

Below is an example of how to use reflection and Fluent API to define the models for your DbContext. (This is a VB.NET version of my previous GIST)

Objective

To contain the definition and initialization of a model in a single file and to seperate initialization out of the main context file.

IEntityBuilder.cs

The interface "IEntityBuilder" is primarily used to identify the models that are to be built

User.cs

This is a sample of a model for a "User" object: This class implements IEntityBuilder and therefore the "BuildModel" method.

MyDatabaseContext.cs

A simplified example of the generated Context file showing the required changes.

Imports System.Data.Entity
Public Interface IEntityBuilder
Sub BuildModel(ByVal modelBuilder As DbModelBuilder)
End Interface
Imports System.Data.Common
Imports System.Data.Entity
Imports System.Reflection
Public Class MyDataContext
Inherits DbContext
Public Sub New()
MyBase.New("name=MyDbContext")
End Sub
Public Sub New(ByVal connection As DbConnection)
MyBase.New(connection, True)
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
Dim entityBuilderTypes As IEnumerable(Of Type) = Assembly.GetExecutingAssembly().GetTypes().Where(Function(asyType) asyType.GetInterfaces().Contains(GetType(IEntityBuilder)))
Dim typesWithConstructors As IEnumerable(Of Type) = entityBuilderTypes.Where(Function(ebType) Not ebType.GetConstructor(Type.EmptyTypes) Is Nothing)
For Each type As Type In typesWithConstructors
Dim createdInstance As IEntityBuilder = Activator.CreateInstance(type)
createdInstance.BuildModel(modelBuilder)
Next
End Sub
End Class
Imports System.ComponentModel.DataAnnotations.Schema
Imports System.Data.Entity
Partial Public Class User
Implements IEntityBuilder
<DatabaseGenerated(DatabaseGeneratedOption.Identity)>
Public Property Id As Integer
Public Property FirstName As String
Public Property LastName As String
Public Property UserName As String
Public Property EmailAddress As String
Public Sub BuildModel(modelBuilder As DbModelBuilder) Implements IEntityBuilder.BuildModel
modelBuilder.Entity(Of User)() _
.ToTable("User")
modelBuilder.Entity(Of User)() _
.Property(Function(e) e.FirstName) _
.HasColumnName("FirstName") _
.IsUnicode(False) _
.HasMaxLength(20) _
.IsRequired()
End Sub
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment