我正在尝试使用 Entity Framework 的代码优先概念创建一个新数据库。然而,当运行代码时,数据库没有创建(使用 DropCreateDatabaseIfModelChanges
设置),尽管代码运行良好。当我尝试从数据库中获取某些内容时,我看到了以下异常。
我的项目是使用具有通用服务和存储库构造的单独 DataAccess
层设置的。所以我所有的实体、存储库和数据库上下文都在解决方案中的一个单独项目中。
我的 global.asax
文件包含以下代码。
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
如果不存在,这应该会初始化一个新数据库,对吗?
我的数据库上下文类如下所示;
namespace Website.DAL.Model
{
public class MyContext : DbContext
{
public IDbSet<Project> Projects { get; set; }
public IDbSet<Portfolio> Portfolios { get; set; }
/// <summary>
/// The constructor, we provide the connectionstring to be used to it's base class.
/// </summary>
public MyContext()
: base("MyConnectionString")
{
}
static MyContext()
{
try
{
Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// This method prevents the plurarization of table names
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
}
}
我根据 Internet 上的一些教程和文章创建了这个类(class)。这对我来说都是新的,但据我所知,到目前为止一切似乎都是正确的。所以现在我正在使用的两个实体。它们被称为“项目”和“投资组合”。它们看起来像这样;
public class Portfolio
{
[Key]
public Guid Id { get; set; }
public String Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool IsPublished { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
和
public class Project
{
[Key]
public Guid Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool IsPublished { get; set; }
public String Title { get; set; }
}
我正在使用的数据库在外部服务器上运行,它与我正在使用的托管服务提供商一起提供。我已经启动并运行了一个 SQL Server 数据库,数据库的连接字符串位于网站项目的 web.config
中。我已经尝试删除数据库并让代码重新创建它,不幸的是这没有用。我在这里遗漏了一些明显的东西吗?或者它可以是一个简单的事情,比如对服务器的访问权限来创建数据库?
注意:当我运行 Database-Update -Script
命令生成 SQL 代码时,似乎创建了创建所有表的正确 SQL 语句。
更新 1: 好的,多亏了一些评论,我走得更远了。我已经向我的实体添加了两个属性以强制进行一些更改,并且我还创建了一个像这样的自定义初始化程序;
public class ForceDeleteInitializer : IDatabaseInitializer<MyContext>
{
private readonly IDatabaseInitializer<MyContext> _initializer = new DropCreateDatabaseIfModelChanges<MyContext>();
public ForceDeleteInitializer()
{
//_initializer = new ForceDeleteInitializer();
}
public void InitializeDatabase(MyContext context)
{
//This command is added to prevent open connections. See http://stackoverflow.com/questions/5288996/database-in-use-error-with-entity-framework-4-code-first
context.Database.ExecuteSqlCommand("ALTER DATABASE borloOntwikkel SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
_initializer.InitializeDatabase(context);
}
}
我还从上下文的构造函数中删除了初始化器,所以这意味着我已经删除了这行代码;
Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
之后,我将这三行添加到我的 Global.asax 文件中;
Database.SetInitializer(new ForceDeleteInitializer());
MyContext c = new MyContext();
c.Database.Initialize(true);
在调试时,我现在遇到了这个异常;
这为我提供了以下信息:
- InnerException 说:提供者没有返回 ProviderManifestToken
- InnerException 中的 InnerException 说:“对于此操作,需要连接到 masterdatabase。连接不能 使宽度成为“主”数据库,因为原始连接是 打开并且引用已从连接中删除。 请提供一个未打开的连接”
在这些操作之后数据库无法访问,所以很可能被删除了..
有什么办法可以解决这个问题?我很可能无法访问 master 数据库,因为我的托管服务提供商当然不会给我适当的访问权限。
最佳答案
由于没有其他解决方案,我决定改变我的方法。
我首先自己创建了数据库,并确保配置了正确的 SQL 用户并且我可以访问。
然后我从 Global.asax 文件中删除了初始化程序和代码。之后,我在包管理器控制台中运行了以下命令(由于分层设计,我必须在控制台中选择正确的项目);
Enable-Migrations
启用迁移后,我对我的实体进行了最后一刻的更改,我运行了下面的命令来构建新的迁移;
Add-Migration AddSortOrder
创建迁移后,我在控制台中运行了以下命令,瞧,数据库已更新为我的实体;
Update-Database -Verbose
为了能够在运行迁移时为数据库设定种子,我覆盖了我的 Configuraton.cs 类中的 Seed 方法,该类是在启用迁移时创建的。该方法中的最终代码是这样的;
protected override void Seed(MyContext context)
{
// This method will be called after migrating to the latest version.
//Add menu items and pages
if (!context.Menu.Any() && !context.Page.Any())
{
context.Menu.AddOrUpdate(
new Menu()
{
Id = Guid.NewGuid(),
Name = "MainMenu",
Description = "Some menu",
IsDeleted = false,
IsPublished = true,
PublishStart = DateTime.Now,
LastModified = DateTime.Now,
PublishEnd = null,
MenuItems = new List<MenuItem>()
{
new MenuItem()
{
Id = Guid.NewGuid(),
IsDeleted = false,
IsPublished = true,
PublishStart = DateTime.Now,
LastModified = DateTime.Now,
PublishEnd = null,
Name = "Some menuitem",
Page = new Page()
{
Id = Guid.NewGuid(),
ActionName = "Some Action",
ControllerName = "SomeController",
IsPublished = true,
IsDeleted = false,
PublishStart = DateTime.Now,
LastModified = DateTime.Now,
PublishEnd = null,
Title = "Some Page"
}
},
new MenuItem()
{
Id = Guid.NewGuid(),
IsDeleted = false,
IsPublished = true,
PublishStart = DateTime.Now,
LastModified = DateTime.Now,
PublishEnd = null,
Name = "Some MenuItem",
Page = new Page()
{
Id = Guid.NewGuid(),
ActionName = "Some Action",
ControllerName = "SomeController",
IsPublished = true,
IsDeleted = false,
PublishStart = DateTime.Now,
LastModified = DateTime.Now,
PublishEnd = null,
Title = "Some Page"
}
}
}
});
}
if (!context.ComponentType.Any())
{
context.ComponentType.AddOrUpdate(new ComponentType()
{
Id = Guid.NewGuid(),
IsDeleted = false,
IsPublished = true,
LastModified = DateTime.Now,
Name = "MyComponent",
PublishEnd = null,
PublishStart = DateTime.Now
});
}
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
//foreach (var eve in e.EntityValidationErrors)
//{
// Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
// eve.Entry.Entity.GetType().Name, eve.Entry.State);
// foreach (var ve in eve.ValidationErrors)
// {
// Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
// ve.PropertyName, ve.ErrorMessage);
// }
//}
//throw;
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format(
"- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage));
}
}
System.IO.File.AppendAllLines(@"c:\temp\errors.txt", outputLines);
throw;
}
}
目前的缺点是我必须在包管理器控制台中使用(仅)2 个命令手动迁移。但与此同时,这不是动态发生的事实也很好,因为这可以防止对我的数据库进行可能不需要的更改。此外,一切都非常完美。
关于c# - Entity Framework 5 代码优先不创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17601459/