2015-08-28 38 views
0

我正在關注asp.net MvcMusicStore教程,一切正常,但數據沒有添加到MvcMusicStore.sdf ...這是與教程的那部分連接數據庫的頁面:http://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-4 預期的結果應該返回一個包含所有流派的列表,但在我的情況下,我在MvcMusicStore.sdf流派表中獲得NULL值。MvcMusicStore數據庫連接

我下載了完整的教程,一切工作正常有,值插入到數據庫表中的所有數據..

SampleData.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Data.Entity; 

namespace MvcMusicStore.Models 
{ 
    public class SampleData : DropCreateDatabaseIfModelChanges<MusicStoreEntities> 
    { 
     protected override void Seed(MusicStoreEntities context) 
     { 
      var genres = new List<Genre> 
      { 
       new Genre { Name = "Rock" }, 
       new Genre { Name = "Jazz" }, 
       new Genre { Name = "Metal" } 
      }; 

      var artists = new List<Artist> 
      { 
       new Artist { Name = "Aaron Copland & London Symphony Orchestra" }, 
       new Artist { Name = "Aaron Goldberg" } 
      }; 

      new List<Album> 
      { 
       new Album { Title = "A Copland Celebration, Vol. I", Genre = genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Aaron Copland & London Symphony Orchestra"), AlbumArtUrl = "/Content/Images/placeholder.gif" }, 
      }.ForEach(a => context.Albums.Add(a)); 
     } 
    } 
} 

Web.config文件:

<connectionStrings> 
    <add name="MusicStoreEntities" 
    connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf" 
    providerName="System.Data.SqlServerCe.4.0"/> 
    </connectionStrings> 

Global.asax

protected void Application_Start() 
{ 
    System.Data.Entity.Database.SetInitializer(
     new MvcMusicStore.Models.SampleData()); 
    AreaRegistration.RegisterAllAreas(); 
    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 
} 

Genre.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace MvcMusicStore.Models 
{ 
    public partial class Genre 
    { 
     public int GenreId { get; set; } 
     public string Name { get; set; } 
     public string Description { get; set; } 
     public List<Album> Albums { get; set; } 
    } 
} 
+0

可能你也許發表您的風格類的模式? –

+0

'DataDirectory'確實取代了這個? – Sherlock

+0

@MatthiasBurger我更新了流派類的代碼 – Valip

回答

0

你是不是有效的加入流派和藝術家到數據庫中。

context.Albums.Add(a)將相冊添加到上下文中,但缺少類型和藝術家的等效調用。 以下各行應添加:

  • context.Artists.AddRange(artists)
  • context.Genres.AddRange(genres)
+0

我已經添加了這些代碼行,但現在我在AddRange上收到以下錯誤:'System.Data.Entity.DbSet '沒有包含「AddRange」的定義,並且沒有找到接受類型爲「System.Data.Entity.DbSet 」的第一個參數的擴展方法「AddRange」(可以找到(你是否缺少using指令或組裝參考?) – Valip

+0

你在哪裏添加了代碼? 正如你可以看到[這裏](https://msdn.microsoft.com/en-us/library/system.data.entity.dbset.addrange(v = vs.113).aspx),DbSet支持這些方法類型。 也許你錯過了一些命名空間或引用。 – BKR