gpt4 book ai didi

entity-framework - EF - code first - 自动更新数据库

转载 作者:行者123 更新时间:2023-12-04 07:23:04 24 4
gpt4 key购买 nike

我想在我的代码中使用自动迁移,但每次我更改模型中的某些内容时,我都需要手动运行 update-Database。我可以自动执行吗?

这是配置:

public class Configuration : DbMigrationsConfiguration<ManualContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
...
}

AppActivator:

[assembly: WebActivator.PreApplicationStartMethod(typeof(AppActivator), "PreStart")]
[assembly: PostApplicationStartMethod(typeof(AppActivator), "PostStart")]
[assembly: ApplicationShutdownMethod(typeof(AppActivator), "Stop")]

namespace Manual.Web
{
public static class AppActivator
{
public static void PreStart()
{
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<ManualContext,Configuration>());
Database.SetInitializer(new ManualDbInitializer());

MeasurementConfig.RegisterUnits();
MiniProfilerPreStart();
}
...
}

和 ManualDbInitializer - 用于种子(第一次创建数据库时):

public class ManualDbInitializer : CreateDatabaseIfNotExists<ManualContext>
{
protected override void Seed(ManualContext context)
{
ManualDbInitializerSeed.SeedForDB(context);
}
}

最佳答案

If you are deploying your application you may want it to automatically upgrade the database (by applying any pending migrations) when the application launches. You can do this by registering the MigrateDatabaseToLatestVersion database initializer. A database initializer simply contains some logic that is used to make sure the database is setup correctly. This logic is run the first time the context is used within the application process (AppDomain).

http://msdn.microsoft.com/en-us/data/jj591621#initializer

关于entity-framework - EF - code first - 自动更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26212490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com