2012-02-25 122 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

相關問題