1. 首先推荐刚开始使用EF的同学先看下这篇文章。
http://www.cnblogs.com/shijun/archive/2012/11/16/2772676.html 踩过坑后才找到这篇文章然后恍然大悟!再次谢谢分享这篇文章的同学。
2.下面是我参考的教程的链接
http://www.shaoqun.com/a/91504.aspx
3.以下是我按照教程做单过程中踩过的坑
运行命令Enable-Migrations
3.1直接贴错误信息
More than one context type was found in the assembly 'WebApplication5'.
To enable migrations for 'WebApplication5.Models.ConnectionstringContext', use Enable-Migrations -ContextTypeName WebApplication5.Models.ConnectionstringContext.
To enable migrations for 'WebApplication5.Models.ApplicationDbContext', use Enable-Migrations -ContextTypeName WebApplication5.Models.ApplicationDbContext.
3.2正确做法
PM> Enable-Migrations -ContextTypeName WebApplication5.Models.ConnectionstringContext
3.33. PM> Update-Database
报错信息
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.System.InvalidOperationException: No connection string named 'MusicContext' could be found in the application config file.
at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
No connection string named 'MusicContext' could be found in the application config file.
修改办法,直接写入链接字符串
public ConnectionstringContext() : base("Data Source = .;initial catalog=Music;integrated security=True"){ }
再次运行还是报错,信息如下;
数据库中已存在名为 'Musics' 的对象。
解决办法:
直接怒删数据库表
重新输入命令
PM> Update-Database 输出正确信息,并且数据库表单更新完毕。
总结:code first 模式只适合新建数据库表,不适合修改。若有不准确的地方欢迎拍砖。