I am learning ASP.NET and I am using EF Core in my project. I would like to seed some test data when I'm running my migrations. Here's my AppDbContext
class and my model classes:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Game> Games { get; set; }
public DbSet<Studio> Studios { get; set; }
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
var converter = new EnumToNumberConverter<Genre, byte>();
builder.Entity<Game>().Property(item => item.Genre).HasConversion(converter);
}
}
public class Person
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(30)]
public string Name { get; set; }
[Required]
[StringLength(30)]
public string Surname { get; set; }
}
public class Game
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[Range(0.0, 1000.0)]
public double Price { get; set; }
public Genre Genre { get; set; }
[Required]
public Studio Studio { get; set; }
}
public class Studio
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public IEnumerable<Game> Games { get; set; }
[Required]
public decimal Budget { get; set; }
public IEnumerable<Person> Employees { get; set; }
}
As you could notice there's a little bit complicated relation between Game and Studio entities. Not only game has a studio which created the game, but also a studio has a list of games developed by them.
If I had to write OnModelCreating
method, I would firstly create some test people and then use them to fill Employees
field in Studio
class. The problem occurs when I have to create games. Studio does not exist yet and if I wanted to create studios first, games are a missing element.
Do I have to manually create some games, ignoring the Studio reference, then instantiate studios, and then manually link object together, or is there any better solution? Best regards.