2

我已经尝试解决这个问题已经有一段时间了,但没有运气,猜想对于有经验的人来说这将是一件轻而易举的事。我正在使用 MvcMusicStore。

我有一个数据库上下文,我添加了一张新专辑的新专辑。如果我想添加另一个具有相同流派的专辑,如何将现有流派分配给新专辑?就像下面的第二张专辑一样。提前感谢您的帮助。

protected override void Seed(Models.MusicStoreDBContext context)
        {
            context.Artists.Add(new Models.Artist { Name = "Al Di Meola" });
            context.Genres.Add(new Models.Genre { Name = "Jazz" });
            context.Albums.Add(new Models.Album
            {
                Artist = new Models.Artist { Name = "Sublime" },
                Genre = new Models.Genre { Name = "Rock" },
                Price = 11.99m,
                Title = "40oz to Freedom"
            });
            context.Albums.Add(new Models.Album
            {
                Artist = new Models.Artist { Name = "Jawbox" },
                Genre = "Rock", // HOW DO I ASSIGN THIS?
                Price = 10.99m,
                Title = "For your own special sweetheart"
            });
4

3 回答 3

1

只使用一个变量?

var rock = new Models.Genre{Name="Rock"};
 context.Genres.Add(rock);
 context.Albums.Add(new Models.Album
 {
     Artist = new Models.Artist { Name = "Sublime" },
     Genre = rock,
     Price = 11.99m,
     Title = "40oz to Freedom"
 });
 context.Albums.Add(new Models.Album
 {
     Artist = new Models.Artist { Name = "Jawbox" },
     Genre = rock
     Price = 10.99m,
     Title = "For your own special sweetheart"
 });
于 2013-07-26T11:18:55.027 回答
0

只需将您的新流派分配给一个变量,然后将属性设置为该变量。

var rockGenre = new Models.Genre() { Name = "Rock" };
context.Genres.Add(rockGenre);

context.Albums.Add(new Models.Album
            {
                Artist = new Models.Artist { Name = "Sublime" },
                Genre = rockGenre,
                Price = 11.99m,
                Title = "40oz to Freedom"
            });
            context.Albums.Add(new Models.Album
            {
                Artist = new Models.Artist { Name = "Jawbox" },
                Genre = rockGenre,
                Price = 10.99m,
                Title = "For your own special sweetheart"
            });
于 2013-07-26T11:20:48.260 回答
0

还是子查询?

protected override void Seed(Models.MusicStoreDBContext context)
    {
        context.Artists.Add(new Models.Artist { Name = "Al Di Meola" });
        context.Genres.Add(new Models.Genre { Name = "Jazz" });
        context.Albums.Add(new Models.Album
        {
            Artist = new Models.Artist { Name = "Sublime" },
            Genre = new Models.Genre { Name = "Rock" },
            Price = 11.99m,
            Title = "40oz to Freedom"
        });
        context.Albums.Add(new Models.Album
        {
            Artist = new Models.Artist { Name = "Jawbox" },
            Genre = (context.Genres.FirstOrDefault(x=>x.Name=="Rock")),
            Price = 10.99m,
            Title = "For your own special sweetheart"
        });

    }
于 2013-07-26T11:35:10.090 回答