如何启用迁移以在MVC4中更新我的数据库?
我正在使用Visual Studio 2012中的MVC4进行项目,并在表中添加了一列。
现在,当我想调试我的项目时,错误说使用迁移来更新我的数据库。
我该怎么办?
我一直在搜索,发现了一些方法,如:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer(null); }
但不知道如何以及在何处实现这个…已经尝试过app_start
, global.asax
等…
我发现的是,从nuget直接在控制台中启用迁移。
但我无法做到这一点。
我使用的命令:
Enable-Migrations -EnableAutomaticMigrations
==>控制台说找到了多个上下文。 要启用use,请Enable-Migrations -ContextTypeName NameOfTheNamespace.Models.DefaultConnection
但我不知道什么是-ContextTypeName
,已经尝试了很多但无法理解。
My Model Code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Data.Entity.Migrations; using System.ComponentModel.DataAnnotations; using System.Data.Entity.Infrastructure; namespace Vista.Models { public class TabelaIndex { public int ID { get; set; } public string n_empresa { get; set; } public string titulo{ get; set; } public string url { get; set; } public string imagens { get; set; } } public class DefaultConnection : DbContext { public DbSet ResTabelaIndex { get; set; } } }
错误是说你有两个上下文。 当您首次使用MVC 4创建项目时,Visual Studio默认为您的SimpleMembership
创建一个上下文(检查Models / Account.cs)或为UsersContext
执行ctrl+f
,如果您不使用SimpleMembership
,则可以删除此文件。 删除此上下文后,继续并将以下内容添加到DefaultConnection
类:
protected override void OnModelCreating(DbModelBuilder builder) { Database.SetInitializer(new MigrateDatabaseToLatestVersion()); }
如果您正确启用了迁移,则还应该有一个名为Migrations
的文件夹,其中包含一个Configuration
类,其构造函数应如下所示(如果要启用自动迁移):
public Configuration() { AutomaticMigrationsEnabled = true; }
命令:
-
enable-migrations default context
-
add-migration InitialCreate
(用于生成快照) -
add-migration InitialCreate
(应用快照) -
update-database
-
update-database -verbose
详细的探索将在这里: http : //www.dotnet-tricks.com/Tutorial/entityframework/R54K181213-Understanding-Entity-Framework-Code-First-Migrations.html
尝试在控制台中键入:
Enable-Migrations -ContextTypeName Vista.Models.DefaultConnection
Vista.Models.DefaultConnection是您的上下文(inheritance自DbContext的类)。
如果您有小的更改,则不需要迁移。 您可以使用sql脚本将列添加到数据库上的任何表,并将属性添加到模型和删除元数据表。 (首先毫无疑问备份数据库)。
或者你可以使用这样的迁移: aspnet-mvc-4-entity-framework-scaffolding-and-migrations
上述就是C#学习教程:如何启用迁移以在MVC4中更新我的数据库?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1038908.html