Skip to content

Instantly share code, notes, and snippets.

@ChrisMissal
Last active August 30, 2019 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisMissal/cc9c008af2dbaa0bc6d351b8747f6d09 to your computer and use it in GitHub Desktop.
Save ChrisMissal/cc9c008af2dbaa0bc6d351b8747f6d09 to your computer and use it in GitHub Desktop.
Example of Partial DbContext and interface for mocking/testing.

About

The file WorkifyEntities.Context.cs is what EF generates for us, or in EF Core, you can create yourself on top of the base class.

The Entities.cs file, we create our own partial class, and assign an interface. From here, we will register our own interface while the instance will be the DbContext.

Usage

Just inject the interface and use it. You will have to add properties and methods to the interface to match the DbContext.

Testing

We've been using this library to help us mock out the DBSet collections: https://www.nuget.org/packages/EntityFrameworkTesting/

namespace DimensionsUpdate.Storage
{
public partial class WorkifyEntities : IWorkifyEntities
{
}
public interface IWorkifyEntities
{
DbSet<UserDimension> UserDimensions { get; }
DbSet<AspNetUser> AspNetUsers { get; }
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DimensionsUpdate.Storage
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class WorkifyEntities : DbContext
{
public WorkifyEntities()
: base("name=WorkifyEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<UserDimension> UserDimensions { get; set; }
public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment