簡體   English   中英

在startup.cs中播種數據

[英]Seeding data in startup.cs

可以在startup.cs中播種數據嗎? 在那里而不是在DbContext或遷移配置類中這樣做是否有優點和缺點?

public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
    SeedData();
}
public void SeedData()
{
    using (ApplicationDbContext _db = new ApplicationDbContext())  {
        if (!_db.Books.Any(n => n.Name == "Seeded in Startup.cs"))
        {
            _db.Books.Add(new Book() { Name = "Seeded in Startup.cs", Date = "1966" });
        }
        _db.SaveChanges();
    }
}

我們創建了一個SeedHelpers.cs。在此文件中,所有種子數據均可用。

public async Task Seed()
        {
            try
            {
                if (RoleManager.Roles.ToList().Count == 0)
                    foreach (string role in typeof(RoleConst).GetConstValue<string>())
                        await RoleManager.CreateAsync(new RoleEntity { Name = role.ToString() });

                if (UserManager.Users.ToList().Count == 0)
                {
                    UserEntity entity = new UserEntity
                    {
                        Email = "y",
                        Active = true,
                        Deleted = false,
                        EmailConfirmed = true,
                        Created = DateTime.UtcNow,
                        Modified = DateTime.UtcNow,
                        Name = "y",
                        UserName = "x"
                    };
                    await UserManager.CreateAsync(entity, "fg@123");
                    await UserManager.AddToRoleAsync(entity, RoleConst.Admin);
                    //Send Invitation email to Admin in the Production.
                }
                if(DapperLanguage.All().ToList().Count()==0)
                {
                    await DapperLanguage.AddAsync(new Language
                    {
                        Id = Guid.NewGuid(),
                        Code = LanguageConst.English,
                        Name = "English"
                    });
                    await DapperLanguage.AddAsync(new Language
                    {
                        Id = Guid.NewGuid(),
                        Code = LanguageConst.Arabic,
                        Name = "Arabic"
                    });
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError(JsonConvert.SerializeObject(new { class_name = this.GetType().Name, exception = ex }));
            }
        }

並在Startup.cs文件中

public void Configuration(IAppBuilder app, Helpers.SeedHelpers seed)
{
    ConfigureAuth(app);
    seed.Seed().Wait();
}

嘗試這種類型的方法。

如果您正在使用ef core,現在可以在ef映射配置中使用HasData():

https://docs.microsoft.com/zh-cn/ef/core/modeling/data-seeding

如果使用ef 6,則可以在DbContext上設置初始化程序,並且可以將每個實體的種子數據存儲在單獨項目中的單獨文件中?

http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM