bchavez / bchavez/Bogus

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

Open
#433 1 comment 0 reactions 0 assignees View on GitHub
question
Dominant language
C#
Stars
9.7k
Forks
538
PR merge metrics
No merged PRs in 30d

Description

### 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](https://github.com/bchavez/Bogus/tree/master/Examples/EFCoreSeedDb) 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 options) : base(options)
{
}
public DbSet CatalogItems { get; set; }

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

FakeData.Init(10);

builder.Entity().HasData(FakeData.CatalogItems);
}
}

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

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

var catalogItemFaker = new Faker()
.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; }
}
}

Contributor guide

Open the contributing guide

Research direction

Read Examples/EFCoreSeedDb and the CatalogDbContext.OnModelCreating method shown in the issue, then trace how the DbContext is created in unit tests versus the deployed API. Done means fake HasData seeding occurs for the test DbContext without being applied when the application is deployed.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
databases, testing
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.