编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

EF-代码优先-自动更新数据库:EF - code first - automatic update database

Badmaash 数据库/缓存 2022-5-11 10:24 6人围观

腾讯云服务器
EF-代码优先-自动更新数据库的处理方法

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

I want to use automatic migrations in my code, but every time I change something in the model I need to run update-Database manually. Can I do it automatically?

这是配置:

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-用于种子(第一次创建数据库时):

And ManualDbInitializer - for seed (when creating DB at first time):

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

问题解答

如果要部署应用程序,则可能希望它在应用程序启动时自动升级数据库(通过应用任何挂起的迁移).您可以通过注册MigrateDatabaseToLatestVersion数据库初始化程序来实现.数据库初始化程序仅包含一些用于确保正确设置数据库的逻辑.第一次在应用程序流程(AppDomain)中使用上下文时,将运行此逻辑.

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

这篇关于EF-代码优先-自动更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^