实体框架代码优先,不生成数据库

本文关键字:数据库 框架 代码 实体 | 更新日期: 2023-09-27 18:25:57

我对使用代码优先建模数据库完全陌生。我试着遵循了几个不同的教程,但都遇到了问题,一直不知道为什么。

现在我有一个新的MVC 4项目。我和另外三个人一起做这个项目,我们使用TeamFoundationServer进行源代码管理。根据各种教程,我设置了我的模型如下:

public class User
{
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Entry> Entries { get; set; }
    public virtual ICollection<Rating> Ratings { get; set; }
}
public class Contest
{
    public int ContestId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public Boolean Published { get; set; }
    public virtual ICollection<Submission> Submissions { get; set; }
    public virtual ICollection<Tab> Tabs { get; set; }
}
public class Tab
{
    public int TabId { get; set; }
    public string Name { get; set; }
    public int Order { get; set; }
    public string Content { get; set; }
    public int ContestId { get; set; }
public virtual Contest Contest { get; set; }
}
public class Entry
{
    public int EntryId { get; set; }
    public string Title { get; set; }
    public string EmbedURL { get; set; }
    public string Description { get; set; }
    public Boolean isApproved { get; set; }
    public int UserId { get; set; }
    public virtual ICollection<Submission> Submissions { get; set; }
    public virtual User User { get; set; }
}
public class Submission
{
    public int SubmissionId { get; set; }
    public DateTime Submitted { get; set; }
    public int EntryId { get; set; }
    public int ContestId { get; set; }
    public virtual Entry Entry { get; set; }
    public virtual Contest Contest { get; set; }
}
public class Rating
{
    public int RatingId { get; set; }
    public int Stars { get; set; }
    public int UserId { get; set; }
    public int SubmissionId { get; set; }

    public virtual User User { get; set; }
    public virtual Submission Submission { get; set; }
}

并创建了DbContext:的扩展

public class CPContext : DbContext
{
    public CPContext() : base("name=CPContext")
    {
    }
    public DbSet<Contest> Contests { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Entry> Entries { get; set; }
    public DbSet<Submission> Submissions { get; set; }
    public DbSet<Rating> Ratings { get; set; }
    public DbSet<Tab> Tabs { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

最后,我的Web.config文件中的连接字符串:

<add name="CPContext" connectionString="Data Source=.'SQLEXPRESS;Initial Catalog=aspnet_ContestPlatform;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

除此之外,我正在用下面的测试数据初始化我的数据库:

//Will seed the database with dummy values when accessed for first time
public class ContestPlatformInitializer : DropCreateDatabaseIfModelChanges<CPContext>
{
    protected override void Seed(CPContext context)
    {
        var users = new List<User>
        {
            new User { FirstName = "Daniel", LastName = "Hines", Email = "hinesd@blah.edu" },
            new User { FirstName = "Peter", LastName = "Pan", Email = "panp@blah.edu" },
            new User { FirstName = "Marie", LastName = "VerMurlen", Email = "vermurle@blah.edu" },
            new User { FirstName = "Aaron", LastName = "Brown", Email = "browna5@blah.edu" }
        };
        users.ForEach(s => context.Users.Add(s));
        context.SaveChanges();
        var entries = new List<Entry>
        {
            new Entry { UserId = 1, Title = "Flight Simulation", EmbedURL = "www.blah.com/video1", Description = "This is an awesome app!", isApproved = true },
            new Entry { UserId = 2, Title = "Underwater Explorer", EmbedURL = "www.blah.com/video1", Description = "This is an awesome app!!", isApproved = true },
            new Entry { UserId = 3, Title = "Dress-Up", EmbedURL = "www.blah.com/video1", Description = "This is an awesome app!!!", isApproved = true },
            new Entry { UserId = 4, Title = "Combat Training", EmbedURL = "www.blah.com/video1", Description = "This is an awesome app!!!!", isApproved = true },
            new Entry { UserId = 1, Title = "Fitness Pro", EmbedURL = "www.blah.com/video1", Description = "This is an awesome app!!!!!", isApproved = true }
        };
        entries.ForEach(s => context.Entries.Add(s));
        context.SaveChanges();
        var contests = new List<Contest>
        {
            new Contest { Name = "Game Contest", Description = "This contest is to see who can make the most awesome game!", Start = DateTime.Parse("2012-02-10"), End = DateTime.Parse("2012-04-20"), Published = true },
            new Contest { Name = "App Contest", Description = "This contest is to see who can make the coolest app!", Start = DateTime.Parse("2012-03-10"), End = DateTime.Parse("2012-09-20"), Published = false }
        };
        contests.ForEach(s => context.Contests.Add(s));
        context.SaveChanges();
        var tabs = new List<Tab>
        {
            new Tab { ContestId = 1, Name = "Rules", Content = "The first rule is that there are no rules!", Order = 1 },
            new Tab { ContestId = 2, Name = "Examples", Content = "No examples here yet, check back soon.", Order = 1}
        };
        tabs.ForEach(s => context.Tabs.Add(s));
        context.SaveChanges();
        var submissions = new List<Submission>
        {
            new Submission { ContestId = 1, EntryId = 1, Submitted = DateTime.Parse("2-13-2012") },
            new Submission { ContestId = 1, EntryId = 2, Submitted = DateTime.Parse("2-14-2012") },
            new Submission { ContestId = 1, EntryId = 3, Submitted = DateTime.Parse("2-15-2012") },
            new Submission { ContestId = 1, EntryId = 4, Submitted = DateTime.Parse("2-16-2012") },
        };
        submissions.ForEach(s => context.Submissions.Add(s));
        context.SaveChanges();
        var ratings = new List<Rating>
        {
            new Rating { Stars = 4, UserId = 1, SubmissionId = 1 },
            new Rating { Stars = 5, UserId = 2, SubmissionId = 1 },
            new Rating { Stars = 2, UserId = 3, SubmissionId = 1 },
            new Rating { Stars = 4, UserId = 4, SubmissionId = 1 },
            new Rating { Stars = 1, UserId = 1, SubmissionId = 2 },
            new Rating { Stars = 2, UserId = 2, SubmissionId = 2 },
            new Rating { Stars = 1, UserId = 3, SubmissionId = 2 },
            new Rating { Stars = 3, UserId = 4, SubmissionId = 2 },
            new Rating { Stars = 5, UserId = 1, SubmissionId = 3 },
            new Rating { Stars = 5, UserId = 2, SubmissionId = 3 },
            new Rating { Stars = 4, UserId = 3, SubmissionId = 3 }
        };
        ratings.ForEach(s => context.Ratings.Add(s));
        context.SaveChanges();
    }
}

它在我的Global.asax文件中的Application_Start()方法中调用。

因此,现在为了测试一切是否正常工作,我为我的Contest模型创建了一个控制器,它生成了一个相应的视图。当我编译应用程序并尝试调用Contest控制器时,会引发异常。

用户代码未处理System.Data.EntityCommandExecutionException消息=执行命令定义时出错。有关详细信息,请参阅内部异常。Source=System.Data.EntityStackTrace:位于System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand EntityCommand,CommandBehavior behavior)位于System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext上下文,ObjectParameterCollection参数值)位于System.Data.Objects.ObjectQuery 1.GetResults(Nullable for MergeOption)位于System.Data.Objects.ObjectQuery 1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() at System.Collections.Generic.List 1..ctor(IEnumerable 1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable 1源)位于C:''Users''Danny''Documents''Visual Studio 2010''Projects''ContestPlatform''ContestPlatform''ContestPlatform''Controllers''ContestController.cs:line 21在lambda_method(闭包、ControllerBase、Object[])位于System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext ControllerContext,IDictionary`2个参数)位于System.Web.Mvc.Anc.AncControllerActionInvoker。<>c_显示类42.b_41()位于System.Web.Mvc.Anc.AncControllerActionInvoker。<>c_显示类37.<>c_DisplayClass39.b_33()位于System.Web.Mvc.Anc.AncControllerActionInvoker。<>c_DisplayClass4f.b_49()InnerException:System.Data.SqlClient.SqlException消息=对象名称"dbo.Contest"无效。Source=.Net SqlClient数据提供程序错误代码=-2146232060等级=16行号=1编号=208程序="服务器=。''SQLEXPRESS状态=1StackTrace:位于System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔breakConnection)位于System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()位于System.Data.SqlClient.TdsParser.Run(RunBehavior RunBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj)位于System.Data.SqlClient.SqlDataReader.ConsumeMetaData()位于System.Data.SqlClient.SqlDataReader.get_MetaData()位于System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior RunBehavior,String resetOptionsString)位于System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior RunBehavior、Boolean returnStream、Boolean async)位于System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior RunBehavior、Boolean returnStream、String方法、DbAsyncResult结果)位于System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior RunBehavior、Boolean returnStream、String方法)位于System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior行为,String方法)位于System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior行为)位于System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand EntityCommand,CommandBehavior behavior)内部异常:

注意到行"Message=无效的对象名称"dbo.Contest",我想再次检查表dbo。实际上,竞争正在产生。

我可以进入Management Studio Express并查看数据库"aspnet_ContestPlatform",但它没有表。

这是我应该看到的数据库吗?为什么没有生成表?同样,如果表不在那里,为什么当应用程序启动时,当数据库应该用测试数据播种时,我没有得到一个异常?

实体框架代码优先,不生成数据库

否,数据库的名称应为[YourNamespace,如果有的话].CPCContext,而不是"aspnet_ContestPlatform"。

我认为你没有立即得到异常的原因是,只有当你遇到使用控制器的视图时,它才会对数据库执行GetResults。有些东西阻止了数据库的创建——不确定是什么——但只要你不从中进行选择,应用程序中就不会出现任何故障。

您是否尝试过修改模型并再次运行应用程序?我经常在我的一个次要实体上保留一个伪属性,我交替地对其进行注释以重新生成数据库。我知道这不是最好的方法,但模型发生了变化,所以数据库应该删除并重新创建。