ASP.NetCore添加Migration时只添加1次种子数据
创始人
2024-09-18 07:01:29
0
  1. 首先,在DbContext中添加一个bool类型的属性,用于指示种子数据是否已添加。在下例中,我们将其命名为_isSeeded:
public class ApplicationDbContext : DbContext
{
    private bool _isSeeded;

    public ApplicationDbContext(DbContextOptions options)
        : base(options)
    {
    }

    // Add entities here
    public DbSet Products { get; set; }
    public DbSet Categories { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Map entities to tables
        modelBuilder.Entity().ToTable("Products");
        modelBuilder.Entity().ToTable("Categories");

        // Add seed data here
        if (!_isSeeded)
        {
            modelBuilder.Entity().HasData(
                new Category { Id = 1, Name = "Electronics" },
                new Category { Id = 2, Name = "Clothing" },
                new Category { Id = 3, Name = "Books" }
            );

            modelBuilder.Entity().HasData(
                new Product { Id = 1, Name = "Laptop", Price = 1000m, CategoryId = 1 },
                new Product { Id = 2, Name = "Smartphone", Price = 800m, CategoryId = 1 },
                new Product { Id = 3, Name = "T-shirt", Price = 10m, CategoryId = 2 },
                new Product { Id = 4, Name = "Jeans", Price = 50m, CategoryId = 2 },
                new Product { Id = 5, Name = "The Catcher in the Rye", Price = 5m, CategoryId = 3 }
            );

            _isSeeded = true;
        }
    }
}
  1. 接下来,在Program.cs文件中配置WebHost,并添加以下代码,以在应用程序启动时应用迁移并添加种子数据:
public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var context = services.GetRequiredService();

            context.Database.Migrate();

            // Manually apply seed data if not already seeded
            if (!context._isSeeded)
            {
                context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [Categories] ON");
                context.Categories.AddRange(
                    new Category { Id = 1, Name = "Electronics" },
                    new Category { Id = 2, Name

相关内容

热门资讯

透视代打!德州局HHpoker... 透视代打!德州局HHpoker透视脚本,新海贝辅助器(透视)开挂辅助工具详细教程 >>您好:软件加薇...
教程书开挂"天天福建... 教程书开挂"天天福建十三张辅助器"开挂(修改器)辅助平台(有挂助手)1、下载安装好天天福建十三张辅助...
原先有辅助"逗娱科技... 原先有辅助"逗娱科技碰胡辅助"开挂(透视)辅助下载(专业教程有挂猫腻)>>您好:软件加1367043...
透视科技!微乐小程序晃晃脚本,... 微乐小程序晃晃脚本是一款专注玩家量身打造的游戏记牌类型软件,在微乐小程序晃晃脚本这款游戏中我们可以记...
积累辅助"蘑菇云辅助... 蘑菇云辅助怎么使用开挂教程视频分享装挂详细步骤在当今的网络游戏中,蘑菇云辅助怎么使用作为一种经典的娱...
原本有辅助"微乐自建... 原本有辅助"微乐自建房脚本免费下载"开挂(透视)辅助软件(安装教程有挂透视) 了解更多开挂安装加(1...
透视游戏!新久久辅助器,财神1... 透视游戏!新久久辅助器,财神13张辅助工具(透视)开挂辅助安装系统教程;无需打开直接搜索加(薇:13...
模块开挂"至友互娱情... 模块开挂"至友互娱情怀辅助"开挂(修改器)辅助插件(有挂工具)至友互娱情怀辅助ai黑科技系统规律教程...
原本有开挂"余干中至... 原本有开挂"余干中至五十k有挂装不"开挂(透视)辅助脚本(黑科技教程有挂解密)您好:余干中至五十k有...
透视了解!好友赣南新版本挂,新... 透视了解!好友赣南新版本挂,新海贝之城辅助(透视)开挂辅助神器2026新版这是一款可以让一直输的玩家...