代码首先,许多人都有额外的领域困境

时间:2012-12-01 18:01:55

标签: c# asp.net-mvc many-to-many code-first

我在MVC4中有一个Playlist类和一个Song类。

规则:

  • 歌曲可以在0个或更多播放列表中。
  • 播放列表可以包含0首或更多首歌曲。

所以我所做的就是创造这个:

public class Playlist
    {
        public int PlaylistID { get; set; }
        public string Name { get; set; }
        public DateTime Date { get; set; }

        public virtual IList<PlaylistSongs> PlaylistSongs { get; set; }
    }

    public class Song
    {
        public int SongID { get; set; }
        public string Title { get; set; }
        public string SongArtURL { get; set; }

        public virtual Artist Artist { get; set; }
        public virtual Genre Genre { get; set; }
        public IList<PlaylistSongs> PlaylistSongs { get; set; }
        public IList<Album> Albums { get; set; }
    }

    public class PlaylistSongs
    {
        public int PlaylistID { get; set; }
        public int SongID { get; set; }

        public virtual Playlist Playlist { get; set; }
        public virtual Song Song { get; set; }

        public int NumberVotes { get; set; }
    }

我也覆盖了OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PlaylistSongs>()
                          .HasKey(cp => new { cp.SongID, cp.PlaylistID });

            modelBuilder.Entity<Playlist>()
                        .HasMany(c => c.PlaylistSongs)
                        .WithRequired()
                        .HasForeignKey(cp => cp.SongID);

            modelBuilder.Entity<Song>()
                        .HasMany(p => p.PlaylistSongs)
                        .WithRequired()
                        .HasForeignKey(cp => cp.PlaylistID);
        }

然而,问题。想象一下,如果我想创建一个Song,它最初没有附加到任何Playlist(工作正常),然后将该歌曲添加到播放列表中。由于播放列表不包含歌曲列表,而是包含播放列表歌曲列表,我该怎么做?

我想要的是:

  • 创建歌曲列表(独立)
  • 将该歌曲列表添加到播放列表
  • 代码优先迁移种子方法然后会在PlaylistSongs表中自动创建所需的关联。
  • 然后我可以让人们在某个播放列表中对歌曲进行投票。
  • 字段NumberVotes会相应更改。

谢谢。

1 个答案:

答案 0 :(得分:1)

改为使用数据注释。将标识字段添加到PlaylistSong类。

    public class PlayList
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime Date { get; set; }

        public virtual IList<PlayListSong> PlaylistSongs { get; set; }
    }

    public class PlayListSong
    {
        [Key]
        public int ID { get; set; }
        public int PlayListID { get; set; }
        public int SongID { get; set; }

        public virtual PlayList Playlist { get; set; }
        public virtual Song Song { get; set; }

        public int NumberVotes { get; set; }
    }

    public class Song
    {
        [Key]
        public int ID { get; set; }
        public string Title { get; set; }
        public string SongArtURL { get; set; }

        //public virtual Artist Artist { get; set; }
        //public virtual Genre Genre { get; set; }
        public IList<PlayListSong> PlaylistSongs { get; set; }
       // public IList<Album> Albums { get; set; }
    }