访问现有数据库上下文属性

时间:2013-07-26 11:16:20

标签: asp.net-mvc linq entity-framework asp.net-mvc-4

我已经尝试解决这个问题很长一段时间没有运气,猜测对于有经验的人来说这将是一件轻而易举的事。我正在使用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"
            });

3 个答案:

答案 0 :(得分: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"
 });

答案 1 :(得分: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"
            });

答案 2 :(得分:0)

或SubQuery?

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

    }