我在MVC4中有一个Playlist
类和一个Song
类。
规则:
所以我所做的就是创造这个:
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
(工作正常),然后将该歌曲添加到播放列表中。由于播放列表不包含歌曲列表,而是包含播放列表歌曲列表,我该怎么做?
我想要的是:
NumberVotes
会相应更改。谢谢。
答案 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; }
}