MvcMusicStore数据库连接

时间:2015-08-28 09:38:44

标签: c# asp.net asp.net-mvc-3

我正在关注asp.net MvcMusicStore教程,一切正常,但数据没有添加到MvcMusicStore.sdf ...这是与教程的那部分建立连接到数据库的页面:{{3} } 预期结果应返回包含所有类型的列表,但在我的情况下,我在MvcMusicStore.sdf Genres表中获取NULL值。

我下载了完成的教程,一切正常,所有数据值都插入到数据库表中。

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; }
    }
}

1 个答案:

答案 0 :(得分:0)

您无法有效地将流派和艺术家添加到数据库中。

context.Albums.Add(a)将相册添加到上下文中,但缺少对流派和艺术家的等效调用。 应添加以下行:

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