带有静态DbInitializer的EF Core和种子数据

时间:2020-08-27 15:04:49

标签: c# entity-framework-core ef-core-2.2

我要实现以下内容: https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-3.1#initialize-db-with-test-data

它可以工作,但是我需要验证是否已添加数据。

我在Internet上找到了以下解决方案:

    public static EntityEntry<TEnt> AddIfNotExists<TEnt, TKey>(this DbSet<TEnt> dbSet, TEnt entity, Func<TEnt, TKey> predicate) where TEnt : class
    {
        var exists = dbSet.Any(c => predicate(entity).Equals(predicate(c)));
        return exists
            ? null
            : dbSet.Add(entity);
    }

    private static void AddRangeIfNotExists<TEnt, TKey>(this DbSet<TEnt> dbSet, IEnumerable<TEnt> entities, Func<TEnt, TKey> predicate) where TEnt : class
    {
        var entitiesExist = from ent in dbSet
                            where entities.Any(add => predicate(ent).Equals(predicate(add)))
                            select ent;

        dbSet.AddRange(entities.Except(entitiesExist));
    }

它对于条件简单(一次检查)的情况很好用,但是我有一个复杂的主键,并且想确定是否已经添加了使用此键的记录:

    public static void Initialize(DataContext context)
    {
        context.Database.EnsureCreated();

        context.DeviceCharacteristicModelMappings.AddIfNotExists(new DeviceCharacteristicModelMapping
        {
            CharacteristicId = 2,
            DeviceModelId = 2
        },  p => new { p.CharacteristicId, DeviceModelId });

        //....

        context.SaveChanges();
    }

,但根本无法编译。如何正确执行?

0 个答案:

没有答案