bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.66k stars 495 forks source link

EF Core DbContext - HasData : Seed Fake Data only from Unit Test and Not when Deployed #433

Open tekbyts opened 2 years ago

tekbyts commented 2 years ago

Version Information

Software Version(s)
Bogus NuGet Package 34.0.2
.NET Core? Yes 6.0
.NET Full Framework? No
Windows OS? Yes Windows 10
Linux OS? No
Visual Studio? 2022

What locale are you using with Bogus?

English

What's the problem?

The example provided in bogus's github repo makes use of the HasData method of the CatalogDbContext class to seed data into the tables.

However, I will not want this HasData method to be executed from the API - meaning, the HasData method should only be run if the DBContext is created from the Unit Tests.

Kindly advise how to achieve this?.

What possible solutions have you considered?

Do you have sample code to show what you're trying to do?

using Bogus;
using Catalog.Api.Database.Entities;
using Microsoft.EntityFrameworkCore;

void Main()
{

}

namespace Catalog.Api.Database
{
    public class CatalogDbContext : DbContext
    {
        public CatalogDbContext(DbContextOptions<CatalogDbContext> options) : base(options)
        {
        }
        public DbSet<CatalogItem> CatalogItems { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.ApplyConfiguration(new CatalogItemEntityTypeConfiguration());

            FakeData.Init(10);

            builder.Entity<CatalogItem>().HasData(FakeData.CatalogItems);
        }
    }

    internal class FakeData
    {
        public static List<CatalogItem> CatalogItems = new List<CatalogItem>();

        public static void Init(int count)
        {
            var id = 1;

            var catalogItemFaker = new Faker<CatalogItem>()
                .RuleFor(ci => ci.Id, _ => id++)
                .RuleFor(ci => ci.Name, f => f.Commerce.ProductName());
        }

    }

    public class CatalogItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
ChristoWolf commented 2 years ago

Not sure if I understand correctly, but why don't you just use this customized CatalogDbContext for unit testing only, and a non-customized context otherwise?