繁体   English   中英

如何实现数据库播种以使用 Entity Framework 进行测试

[英]How to implement database seeding for testing with Entity Framework

我需要为某些应用程序实施测试,但我不确定以易于维护的方式实施测试的最佳和最干净的方法是什么。 场景如下:

我有多个应用程序,包括一个 MVC.Net Framework 项目,以及多个 Azure 函数,其中一个是用 .Net Framework 实现的,因为一些依赖项需要它,但大多数都在 .Net Core 中。 所有这些应用程序都使用 EntityFramework 来操作 MSSQL 数据库,我需要找到一种方法在 memory 或临时数据库中播种默认配置数据和一些预先制作的记录,然后再进行测试。

我想到的一种解决方案是制作一个 Class 库项目,该项目为数据库提供种子,并且每个测试项目都可以引用该项目,当需要将某些内容添加到种子中时,您只需编辑该项目。 但我不知道这是否是最好的解决方案,因为我有 .Net Framework 和 .Net Core 应用程序,所以可能每个 EntityFramework 版本的每个方法至少需要 2 个实现,我不确定是否这样,我的播种机 class 需要知道 DB 模式,或者我可以基于 DBContext class 实现代码。

这会是一个很好的解决方案吗? 有没有其他标准的方式来实现这样的事情?

您的问题有很多假设:根据我的理解,您是否会将相关的 DbContext 传递给您的播种机 class 。 Assuming by 'testing', you mean just putting appropriate test data into a SQL database, then a .NET Core Class Library where your seed class exists is enough; 它只需要了解 DbContext。

播种机示例 class:

using System.Linq;
using System.Threading.Tasks;

using BusinessLogic.Entities;  //this is where your business/EF entities live

namespace DataAccessLayer.Data.Services
{
    public class SeederService
    {
        #region FIELDS
        private readonly TestContext _passedInDbContext;

        #endregion

        #region CONSTRUCTOR
        public SeederService(TestContext passedInDbContext)
        {
            _passedInDbContext = passedInDbContext;
        }

        #endregion

        #region METHODS PUBLIC
        public async Task<bool> SeedDatabaseAsync()
        {
            if (!_passedInDbContext.Currencies.Any()) //see if any entries already exist in the Currency SQL table
            {
                //test data
                _passedInDbContext.Currencies.AddRange
                    (
                        new Currency("GBP", "GBP United Kingdom Pounds", "£", 1.000m),
                        new Currency("USD", "USD United States Dollar", "$", 1.200m),
                        new Currency("EUR", "EUR Euro", "€", 1.100m)
                    );
            }

            await _passedInDbContext.SaveChangesAsync();

            return true;
        }
        #endregion
    }
}

希望这会有所帮助。 当然,您需要设置一个测试 SQL 数据库并使用适当的连接字符串迁移/更新/播种此数据库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM