EntityFrameworkCore - 内存数据库

内存数据库一般用于测试

这里需要注意的是 EntityFramework.Core,InMemory 不是一个关系型数据库, 这就表示内存数据库不关心表之间的联系, 而更注重里面的数据

如果要测试关系的话, 可以使用 SQLite, 下文也会涉及到

 

首先我们有一个很正常的 数据库上下文

public class BloggingContext : DbContext
{
    public BloggingContext()
    { }

    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
        
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;ConnectRetryCount=0");
        }
    }
}

 

和一个 Service 相关功能的类

public class BlogService
{
    private BloggingContext _context;

    public BlogService(BloggingContext context)
    {
        _context = context;
    }

    public void Add(string url)
    {
        var blog = new Blog { Url = url };
        _context.Blogs.Add(blog);
        _context.SaveChanges();
    }

    public IEnumerable<Blog> Find(string term)
    {
        return _context.Blogs
            .Where(b => b.Url.Contains(term))
            .OrderBy(b => b.Url)
            .ToList();
    }
}

 

 

 

下面添加一个测试类(内存数据库)

[TestClass]
public class BlogServiceTests
{
    [TestMethod]
    public void Add_writes_to_database()
    {
        var options = new DbContextOptionsBuilder<BloggingContext>()
            .UseInMemoryDatabase(databaseName: "Add_writes_to_database")
            .Options;

        // Run the test against one instance of the context
        using (var context = new BloggingContext(options))
        {
            var service = new BlogService(context);
            service.Add("http://sample.com");
        }

        // Use a separate instance of the context to verify correct data was saved to database
        using (var context = new BloggingContext(options))
        {
            Assert.AreEqual(1, context.Blogs.Count());
            Assert.AreEqual("http://sample.com", context.Blogs.Single().Url);
        }
    }

    [TestMethod]
    public void Find_searches_url()
    {
        var options = new DbContextOptionsBuilder<BloggingContext>()
            .UseInMemoryDatabase(databaseName: "Find_searches_url")
            .Options;

        // Insert seed data into the database using one instance of the context
        using (var context = new BloggingContext(options))
        {
            context.Blogs.Add(new Blog { Url = "http://sample.com/cats" });
            context.Blogs.Add(new Blog { Url = "http://sample.com/catfish" });
            context.Blogs.Add(new Blog { Url = "http://sample.com/dogs" });
            context.SaveChanges();
        }

        // Use a clean instance of the context to run the test
        using (var context = new BloggingContext(options))
        {
            var service = new BlogService(context);
            var result = service.Find("cat");
            Assert.AreEqual(2, result.Count());
        }
    }
}

 

添加一个 SQLite

[TestClass]
public class BlogServiceTests
{
    [TestMethod]
    public void Add_writes_to_database()
    {
        // In-memory database only exists while the connection is open
        var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        try
        {
            var options = new DbContextOptionsBuilder<BloggingContext>()
                .UseSqlite(connection)
                .Options;

            // Create the schema in the database
            using (var context = new BloggingContext(options))
            {
                context.Database.EnsureCreated();
            }

            // Run the test against one instance of the context
            using (var context = new BloggingContext(options))
            { 
                var service = new BlogService(context);
                service.Add("http://sample.com");
            }

            // Use a separate instance of the context to verify correct data was saved to database
            using (var context = new BloggingContext(options))
            {
                Assert.AreEqual(1, context.Blogs.Count());
                Assert.AreEqual("http://sample.com", context.Blogs.Single().Url);
            }
        }
        finally
        {
            connection.Close();
        }
    }

    [TestMethod]
    public void Find_searches_url()
    {
        // In-memory database only exists while the connection is open
        var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        try
        {
            var options = new DbContextOptionsBuilder<BloggingContext>()
                .UseSqlite(connection)
                .Options;

            // Create the schema in the database
            using (var context = new BloggingContext(options))
            {
                context.Database.EnsureCreated();
            }

            // Insert seed data into the database using one instance of the context
            using (var context = new BloggingContext(options))
            {
                context.Blogs.Add(new Blog { Url = "http://sample.com/cats" });
                context.Blogs.Add(new Blog { Url = "http://sample.com/catfish" });
                context.Blogs.Add(new Blog { Url = "http://sample.com/dogs" });
                context.SaveChanges();
            }

            // Use a clean instance of the context to run the test
            using (var context = new BloggingContext(options))
            {
                var service = new BlogService(context);
                var result = service.Find("cat");
                Assert.AreEqual(2, result.Count());
            }
        }
        finally
        {
            connection.Close();
        }
    }
}

 

posted @ 2018-06-12 14:30  `Laimic  阅读(1547)  评论(0编辑  收藏  举报