Entity Framework Core and Dapper

37.1 Entity Framework Core with VB

EF Core works with VB.NET at runtime. Tooling is C#-centric: migrations generate C# by default, so keep the DbContext/migrations in a C# project, use EF Core Power Tools (which supports VB for reverse engineering), or write migrations manually.

Concepts: DbContext, DbSet, change tracking, navigation properties, Include (eager loading), migrations, AsNoTracking, raw SQL (FromSqlInterpolated), transactions.

On .NET Framework: Entity Framework 6 (EDMX designer or Code First) is supported in VB.

Imports Microsoft.EntityFrameworkCore

Public Class Blog
    Public Property BlogId As Integer
    Public Property Url As String
    Public Property Posts As New List(Of Post)
End Class

Public Class Post
    Public Property PostId As Integer
    Public Property Title As String
    Public Property Content As String
    Public Property BlogId As Integer
    Public Property Blog As Blog
End Class

Public Class BloggingContext
    Inherits DbContext
    Public Property Blogs As DbSet(Of Blog)
    Public Property Posts As DbSet(Of Post)

    Protected Overrides Sub OnConfiguring(options As DbContextOptionsBuilder)
        options.UseSqlite("Data Source=blogging.db")
    End Sub

    Protected Overrides Sub OnModelCreating(modelBuilder As ModelBuilder)
        modelBuilder.Entity(Of Blog)().Property(Function(b) b.Url).IsRequired().HasMaxLength(200)
    End Sub
End Class

Using db As New BloggingContext()
    db.Database.EnsureCreated()
    db.Blogs.Add(New Blog With {.Url = "https://devblogs.microsoft.com/vbteam"})
    db.SaveChanges()

    Dim blogs = db.Blogs.Include(Function(b) b.Posts).
                         Where(Function(b) b.Url.Contains("microsoft")).
                        
…

37.2 Dapper (Micro-ORM)

Dapper is fast and simple. It maps query results to objects and works perfectly from VB.

Imports Dapper
Using conn As New SqlConnection(connStr)
    Dim products = conn.Query(Of Product)("SELECT * FROM Products WHERE Price > @Min", New With {.Min = 100}).ToList()
    Dim one = conn.QuerySingleOrDefault(Of Product)("SELECT * FROM Products WHERE Id = @Id", New With {.Id = 5})
    Dim affected = conn.Execute("UPDATE Products SET Stock = @Stock WHERE Id = @Id", New With {.Stock = 10, .Id = 5})
    Dim count = Await conn.ExecuteScalarAsync(Of Integer)("SELECT COUNT(*) FROM Products")
End Using

37.3 Other Data Options

SQLite (embedded, great for desktop apps), LiteDB (embedded NoSQL), MongoDB.Driver, Microsoft Access via OleDb (Provider=Microsoft.ACE.OLEDB.12.0), Excel via OleDb or ClosedXML.