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 @   `Laimic  阅读(1701)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示