从多对多关系中删除单个关系ef6 c#

时间:2018-02-16 13:33:45

标签: c# entity-framework-6

我正试图从我的多对多关系中删除单个项目(关系),但我尝试过的所有内容似乎都不起作用。

这是我的db:

public class MyContext : DbContext 
{
      public IDbSet<Playlist> Playlists {get; set;}
      public IDbSet<Song> Songs {get; set;}

      //constructor

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
            //some coding for setting up keys and properties

            //relation
            modelBuilder.Entity<Playlist>().HasMany(playlist => playlist.Songs).WithMany(song => song.Playlists);

            //removed cascading
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvetion>();
      }
}

我已经实例化了像

这样的对象
public class Song 
{
    [Key]
    public Guid Id {get; set;}
    //some properties
    public List<Playlist> Playlists {get; set;}

    //in every constructor i made new List<Playlist>() and assigned it to Playlists prop
}


 public class Playlist
 {
     [Key]
     public Guid Id {get; set;}
     //some properties
     public List<Song> Songs {get; set;}
     //I also assigned new List<Song>() to Songs property in every constructor 
 }

现在,我想做的是允许用户不小心地将Song个对象添加/删除到Playlist。我已设法使用async函数进行添加,但在尝试从Song中删除单Playlist时,我会不断遇到各种异常。 我的想法是从所选playlist中的playlists列表中删除song,并为playlist对象执行相同的操作,然后调用该函数来验证db中的更改:

public async Task RemoveSongFromPlaylist()
{
    //await for playlist and song from db

    playlist.Songs.Remove(song);
    song.Playlists.Remove(playlist);
    await db.RemoveRelation(playlist, song);
}


//implementation class for all db doing
public async Task RemoveRelation(playlist, song)
{
     //check if playlist and song even exist in db (only for caution)

     context.Entry(playlist.Songs.First(s => s.Id == song.Id)).State = EntityState.Deleted;
     await context.SaveChangesAsnyc();
}

我真的很感激有关如何做到这一点的任何提示和帮助,虽然我已经挣扎了很多但尝试了很多方法,但每一个都失败了。

1 个答案:

答案 0 :(得分:0)

你的歌曲课不应该包含

List<Playlist>

目前歌曲包含播放列表和播放列表包含歌曲列表,您在此处创建链。这是我看到的问题。

想想YouTube,当您打开播放列表时,您会看到歌曲。但是当您搜索歌曲时,您看不到歌曲包含在

中的播放列表