【问题标题】:EFCore - Seed data only if it doesn't exist in another tableEFCore - 仅在另一个表中不存在时播种数据
【发布时间】:2020-03-16 23:07:49
【问题描述】:

我想在 .net core 3.1 中使用 EntityFramework 播种一些数据,但遇到了一个问题:

我有两个 SQL 表(所以两个 DbSet):

public virtual DbSet<TableA> TableA { get; set; }
public virtual DbSet<TableB> TableB { get; set; }

表 A 的结构如下:

[Key] 
public int Id { get; set; } // PK
public string EnglishText { get; set; } // some value

表 B 的结构如下:

[Key]
public int Id { get; set; } // PK
public int TableAId { get; set; } // FK to Table A
public string TranslatedText { get; set; } // some value

为了为表 A 播种数据,我使用 DBContext 中的 OnModelCreating(ModelBuilder modelBuilder) 方法:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Seed TableA
        modelBuilder.Entity<TableA>().HasData(
            new TableA { Id = 1, EnglishText = "first data"}
        );
    }

然后,我只想在表 B 不包含引用 TableA 的记录(通过 FK)时为其播种,我不确定如何在 OnModelCreating 方法中执行此操作。

我想我在追求类似的东西:

modelBuilder.Entity<TableB>().HasData(var X = new TableB{...}).Where([X.TableAId is not in TableA])

如果有人有想法或可以为我指明方向,将不胜感激。

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    我遇到了完全相同的问题。所以我决定扩展DataBuilder如下:

    using Microsoft.EntityFrameworkCore.Metadata.Builders;
    using System;
    using System.Collections.Generic;
    
    namespace Infrastructure
    {
        static class DataBuilderDynamicData
        {
            private static object asyncObject = new object();
            private static Dictionary<Type, List<EntityBase>> dynamicData = new Dictionary<Type, List<EntityBase>>();
            public static DataBuilder<TEntity> HasDynamicData<TEntity>(this EntityTypeBuilder<TEntity> builder, Func<Dictionary<Type, List<EntityBase>>, TEntity> Resolver) where TEntity : EntityBase
            {
                var targetType = typeof(TEntity);
                TEntity model;
    
                //Note: Not necessary, but just in case several threads reached the same code scope.
                //Note: Lock has some performance hits, but it is negligible due to the fact that Seeding is an In-Design-time process (not run-time).
                lock (asyncObject)
                {
                    model = Resolver(dynamicData);
                    if (dynamicData.ContainsKey(targetType))
                        dynamicData[targetType].Add(model);
                    else
                        dynamicData.Add(targetType, new List<EntityBase> { model });
                }
    
                return builder.HasData(model);
            }
        }
    }  
    

    然后使用它代替HasData(),如下代码:

            foreach (var model in models)
            {
                builder.HasDynamicData<ProvinceMap>((dic) =>
                {
                    //Please note that "Province" should be already seeded with "HasDynamicData" method. Otherwise, you get an error here.
                    var provinces = dic[typeof(Province)];
                    return new ProvinceMap
                    {
                       Id = 1,
                       ProvinceId = provinces.Cast<Province>().First(item => item.Name=="SOME-PROVINCE"),
                       //Some other seed data.
                    };
                });
            }  
    

    请注意EntityBase 是我的自定义基类。您可以改用object。

    public abstract class EntityBase
    {
        public int Id { get; set; }
    }  
    

    每个实体,例如Province 和 ProvinceMap 继承自 EntityBase。
    您可以确保字典已经具有您想要的基本数据(在我的示例中:Province 类),并在我的示例 ProvinceMap 类中将相关配置代码放在消费者类()之前:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration<Province>(new ProvinceConfiguration()); //First, declare the base class.
            modelBuilder.ApplyConfiguration<ProvinceMap>(new ProvinceMapConfiguration()); //Next, declare the consumer class.
        }
    

    您可以实现HasData() 方法的其他重载以满足您的需求。

    【讨论】:

    • 很好,谢谢!
    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 2019-12-01
    • 2019-12-31
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多