EF Core 2.1 HasData() creating deletes and re-inserts for unchanged entities on subsequent migrations

好久不见. 提交于 2019-12-23 14:38:08

问题


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;
        }
    }
}

回答1:


This issue was an EF Core bug that was resolved in EF Core 2.2.



来源:https://stackoverflow.com/questions/52067079/ef-core-2-1-hasdata-creating-deletes-and-re-inserts-for-unchanged-entities-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!