Skip to content

Testing with InMemory #95

@rowanmiller

Description

@rowanmiller

The most important thing is how to scope the database to a single test...

using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddEntityFramework()
                .AddInMemoryDatabase()
                .AddDbContext<SampleContext>(c => c.UseInMemoryDatabase());


            using (var db = serviceCollection.BuildServiceProvider().GetService<SampleContext>())
            {
                db.Blogs.Add(new Blog { Url = "Test" });
                db.SaveChanges();
                Console.WriteLine(db.Blogs.Count());
            }

            using (var db = serviceCollection.BuildServiceProvider().GetService<SampleContext>())
            {
                db.Blogs.Add(new Blog { Url = "Test" });
                db.SaveChanges();
                Console.WriteLine(db.Blogs.Count());
            }
        }
    }

    public class SampleContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions