我正在为 MVC 5 项目使用 EF 6(代码优先与迁移)。在我本地的 DEV 机器上一切正常。
但是,当我将项目部署到 Azure 时,当我的应用程序首次尝试与数据库交互时出现以下错误:
Migrations is enabled for context 'UtilitiesContext' but the database does not exist or
contains no mapped tables. Use Migrations to create the database and its tables, for
example by running the 'Update-Database' command from the Package Manager Console.
我在 Utilities.Data 程序集中有我的 EF 相关代码,我的 MVC 项目在 Utilities.Web 程序集中。
这是我的代码供您参考:
实用程序上下文.cs
public sealed partial class UtilitiesContext : DbContext
{
public UtilitiesContext() : base(Settings.Get(Settings.DB_CONNECTION_STRING)) { }
public DbSet<PreLaunchSubscriber> PreLaunchSubscribers { get; set; }
private void SetCreatedAtUpdatedAt()
{
foreach (DbEntityEntry entityEntry in ChangeTracker.Entries())
{
switch (entityEntry.State)
{
case EntityState.Added:
((IEntity) entityEntry.Entity).CreatedAt = DateTime.Now;
break;
case EntityState.Modified:
((IEntity) entityEntry.Entity).UpdatedAt = DateTime.Now;
break;
}
}
}
[HandleException]
public override int SaveChanges()
{
SetCreatedAtUpdatedAt();
return base.SaveChanges();
}
[HandleException]
public override Task<int> SaveChangesAsync()
{
SetCreatedAtUpdatedAt();
return base.SaveChangesAsync();
}
}
配置.cs
internal sealed class Configuration : DbMigrationsConfiguration<UtilitiesContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Utilities.Data.Contexts.UtilitiesContext";
}
protected override void Seed(UtilitiesContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
设置.cs
public static class Settings
{
public const string DB_CONNECTION_STRING = "DB.ConnectionString";
// other settings ...
public static string Get([Required] string key)
{
return CloudConfigurationManager.GetSetting(key);
}
}
我在选项卡App Settings
部分定义了这个Configuration
:
键:DB.ConnectionString
值:数据源=tcp:host.database.windows.net,1433;初始目录=Utilities;用户ID=user@server;密码=pwd;