iT邦幫忙

2025 iThome 鐵人賽

DAY 30
0
自我挑戰組

打造自己的Medium系列 第 30

Day30 Seeding

  • 分享至 

  • xImage
  •  

最後補充monogodb data seeding,可以不用再額外裝套件

操作

  1. 寫seed
public class MongoDbSeeder
{
    private readonly AppMongoDbContext _context;

    public MongoDbSeeder(AppMongoDbContext dbContext)
    {
        _context = dbContext;
    }

    public async Task SeedAsync()
    {
        bool hasData = await _context.Tags.Find(_ => true).AnyAsync();

        if (!hasData)
        {
            var seedTags = new List<Tag>
            {
                new Tag { Name = "Reading insights" },
                new Tag { Name = "Programming" },
                new Tag { Name = "Mindfulness" },
            };

            await _context.Tags.InsertManyAsync(seedTags);
        }
    }
}
  1. program.cs加入
builder.Services.AddTransient<MongoDbSeeder>();
using (var scope = app.Services.CreateScope())
{
    var seeder = scope.ServiceProvider.GetRequiredService<MongoDbSeeder>();
    await seeder.SeedAsync();
}

作者的哈拉

雖然沒有到棄賽,但也是蠻偏離原本預想的了...
希望下次參加可以先把整體大綱整理好,而不是每天都在趕鴨子上架/images/emoticon/emoticon29.gif


上一篇
Day29 MongoDB Migration
系列文
打造自己的Medium30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言