Update 8/29/18
Seeing this issue in inline new
-ing of seed data as well. Opened an EF Core issue. Will update the question with any findings.
I am trying to use EF Core 2.1's seeding mechanism. However, I want to load the seed data from json flat files rather than hard-coding new C# objects. I wrote the extension method below, which worked well for the initial migration. It looks for files named [MyEntity].json
in DataPath
and deserializes them into objects.
The problem is that if I add a subsequent migration, even without changing a single thing in the models, configurations, or json files, the new migration deletes every single entity and re-inserts them again. So, the Up()
contains a bunch of deletes followed by a bunch of inserts of the same data. I suspect this is because EF Core is not smart enough to recognize that it is an identical set of seed data.
Question:
Is there a way to use EF Core 2.1 seeding with an external data source (such as json files) without having each migration delete and re-insert the data?
My seeding extension method:
public static class ModelBuilderExtensions
{
public static string DataPath { private get; set; } = "..\\..\\data";
public static void Seed<TEntity>(this ModelBuilder modelBuilder) where TEntity : class, IBaseEntity
{
var entities = GetSeedRows<TEntity>();
modelBuilder.Entity<TEntity>().HasData(entities);
}
private static TEntity[] GetSeedRows<TEntity>() where TEntity : IBaseEntity
{
try
{
return JsonConvert.DeserializeObject<TEntity[]>(
File.ReadAllText(DataPath + Path.DirectorySeparatorChar + typeof(TEntity).Name + ".json"));
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
return null;
}
}
}