Custom EntityFramework DbContext with VB.NET – Code first approach

First of all, let me say that I have used EntityFramework many times already but I want to know its inner workings and decided to do it for the starters. That is why I created this blog to share my experience when I did it in vb.net.For the remainder of this blog EF is EntityFramework.

So, now let’s get EF from nuget using package manager console in visual studio. At the time of this writing I am using Visual Studio 2013.

1. Go to package manager console.
PackageManagerConsole

2. Install the latest EF package which currently is 6.1.1.

PackageManagerConsoleConsole

3. Time to create our DbContext. What Im doing here is that I am inheriting from System.Data.Entity.DbContext,

Imports System.Data.Entity
Public Class EFContext
     Inherits DbContext
End Class

4. Lets Assign our connection string to our context.

Public Sub New()
     MyBase.New(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
End Sub

5. Lets create our entity

Public Class Users
     Property UserId As Integer
     Property Username As Integer
     Property FirstName As String
     Property LastName As String
End Class

6. Add our entity to our context

Private _systemUsers As DbSet(Of Users)
Public Property SystemUsers() As DbSet(Of Users)
     Get
          Return _systemUsers
     End Get
     Set(value As DbSet(Of Users))
          _systemUsers = value
     End Set
End Property

7. And finally lets override OnModelCreating method of our base class DbContext. Why I am doing this? Because I am telling our custom DbContext that I have an existing database and I don’t what you to touch it.

Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
     MyBase.OnModelCreating(modelBuilder)
     Database.SetInitializer(Of EFContext)(Nothing)
End Sub

And that is pretty much about it. You now have your custom DbContext using the code first approach.

The complete source is available in github. https://github.com/francorobles/Blog/tree/master/EntityFrameworkVB

Advertisements

One thought on “Custom EntityFramework DbContext with VB.NET – Code first approach

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: