2012-02-25 120 views
2

我完全不熟悉使用代码来建模数据库。我试图遵循几个不同的教程,并遇到所有问题,并且不知道为什么。实体框架代码首先,不生成数据库

现在我有一个新的MVC 4项目。我正在与其他3人合作开发这个项目,我们正在使用Team Foundation Server进行源代码管理。继各种教程,我已经设置了我的模型像这样:

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 = "[email protected]" }, 
      new User { FirstName = "Peter", LastName = "Pan", Email = "[email protected]" }, 
      new User { FirstName = "Marie", LastName = "VerMurlen", Email = "[email protected]" }, 
      new User { FirstName = "Aaron", LastName = "Brown", Email = "[email protected]" } 
     }; 
     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()方法中调用的。

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

System.Data.EntityCommandExecutionException由用户代码未处理 消息=执行命令定义时发生错误。详情请参阅内部例外。 源= System.Data.Entity的 堆栈跟踪: 在System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand,的CommandBehavior行为) 在System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute [TResultType](ObjectContext的上下文中,ObjectParameterCollection的parameterValues) 在System.Data.Objects.ObjectQuery 1.GetResults(Nullable 1 forMergeOption) 在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源) 在ContestPlatform.Controllers.ContestController.Index()在C:\ Users \ Danny \ Documents \ Visual Studio 2010 \ Projects \ ContestPlatform \ ContestPlatform \ ContestPlatform \ Controllers \ ContestController.cs:line 21 at lambda_method(Closure, ControllerBase,Object []) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary`2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker。 <> c_ DisplayClass42.b _41() at System.Web.Mvc.Async.AsyncControllerActionInvoker。 <> c_ DisplayClass37。 <> c _DisplayClass39.b_ 33() at System.Web.Mvc.Async.AsyncControllerActionInvoker。 <> c _DisplayClass4f.b__49() InnerException:System.Data.SqlClient.SqlException Message =无效的对象名称'dbo.Contest'。 源= .net SqlClient数据提供 错误码= -2146232060 类= 16 LineNumber上= 1 总数= 208 过程= “” 服务器= \ SQLEXPRESS 状态= 1个 堆栈跟踪: 在System.Data.SqlClient的.SqlConnection。的OnError(SqlException异常,布尔breakConnection) 在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() 在System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,SqlCommand的cmdHandler,SqlDataReader的数据流,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj) 在System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,String resetOptionsString)System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() .SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔returnStream,布尔异步) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavio r的cmdBehavior,RunBehavior runBehavior,布尔returnStream,String方法,DbAsyncResult结果) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String method) at System.Data.SqlClient.SqlCommand.ExecuteReader (的CommandBehavior行为,字符串方法) 在System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(的CommandBehavior行为) 在System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(entityCommand entityCommand,的CommandBehavior行为) 的InnerException:

注意到行“消息=无效的对象名'dbo.Contest'”,我想双ch eck表dbo.Contest实际上正在生成。

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

这是我应该看到的数据库吗?为什么没有生成表格?此外,如果表格不在那里,为什么当应用程序启动时数据库应该使用测试数据进行播种时,我没有得到正确的例外?

回答

1

不,数据库的名称应该是[YourNamespace,如果有] .CPContext,而不是“aspnet_ContestPlatform”。

我想你没有得到一个立即的异常的原因是因为它只是当你点击视图使用控制器,实际上执行你的GetResults对数据库的结果。有些东西阻止了数据库的创建 - 不知道是什么 - 但只要你不选择它,就不会在应用程序中失败。

您是否尝试过修改模型,然后再次运行应用程序?我经常在我的一个次要实体上保留一个虚拟属性,我交替发表评论来重新生成数据库。我知道这不是做事的最佳方式,但模型会发生变化,所以数据库应该放弃并重新创建。

+0

修改模型并按照您的建议再次运行,结果相同。我试图使用SQL Server Compact,而不是指定一个不同的连接字符串,并遇到一个全新的问题,得到一个错误,说我没有访问数据库的权限。研究了这个问题并尝试了一百万件事情来解决,但是无论如何,STILL似乎都无法正确地生成一个数据库。 – Danny 2012-02-25 03:28:26

+0

好吧,很难知道发生了什么事情,但另一件可以尝试的事情是:除了一个类以外,从一个简单的属性中除去您的模型中的所有内容。只是评论其余的。并相应地修改CPContext。重新运行,看看是否有什么关于EF不满意的模型。 – 2012-02-25 05:17:06

+0

嗯,我从头开始重新创建了这个项目,并将我的所有代码都复制过来了,出于某种原因它现在可以工作。现在唯一的区别是我没有将它添加到TFS。也许这是问题? – Danny 2012-02-25 17:30:20

相关问题