Data Seeding
🧙♂️ You shall not use EF Core data seeding
When working with Confinity, you should not use the data seeding feature from EF Core, mainly for the following reasons:
- Data seeding from EF Core will execute on all stages
- Data from seeding will not be versioned
- You have to manually set owned properties (like
ConfinityMetadata)
Confinity Data Seeding
As an alternative, you can implement the interface IDataSeeder, which will be automatically executed on application startup. Your IDataSeeder implementation will only get called on an author instance, allowing you to directly replicate the data or let the author publish it.
Priority & Order
By default, Confinity runs data seeders in alphabetical order. To change this order, for instance, to seed common data first that other data seeders use, apply the ConfinityPriority attribute. Data seeders with lower priority values will execute before those with higher priority values.
Examples
In the following example, the IDataSeeding interface is implemented by CategoryDataSeeder. The ShouldRun method has to tell Confinity, whether the data seeding should be executed. The actual data seeding happens in the Run method. Because it is using data from a different data seeder, it defines a priority higher than the default (0).
[ConfinityPriority(1)]
public class CategoryDataSeeder : IDataSeeder
{
public async Task<bool> ShouldRun(IConfinityDbContext dbContext)
{
return !await dbContext.Set<SimpleCategory>().AnyAsync();
}
public async Task Run(IConfinityDbContext dbContext)
{
var categories = new[]
{
new SimpleCategory { Name = "Test A", ImageId = DemoAssetSeeder.AssetId },
new SimpleCategory { Name = "Test B", ImageId = DemoAssetSeeder.AssetId }
};
dbContext.Set<SimpleCategory>().AddRange(categories);
await dbContext.SaveChangesAsync();
}
}
You can also extend the abstract DataSeeding<T> where T : ConfinityEntity class, which already has a simple default implementation of ShouldRun, like the example above. ShouldRun will return true, if the table for the generic entity T is empty.
public class SimpleCategoryDataSeeder : DataSeeder<SimpleCategory>
{
public override async Task Run(IConfinityDbContext dbContext)
{
var categories = new[] { new SimpleCategory { Name = "Test A" }, new SimpleCategory { Name = "Test B" } };
dbContext.Set<SimpleCategory>().AddRange(categories);
await dbContext.SaveChangesAsync();
}
}