3

いくつかの値を追加しようとしているだけでなく、選択した値をデータベースから削除しようとしています。

私は以下のようなコードを使用しています:

[HttpPost]
        public ActionResult SavePlaylist(List<ItemEditViewModel> content, long playlistid, List<long> deleted, string Title)
        {
            var playlist = db.Playlists.Include("PlaylistContents").FirstOrDefault(x => x.PlaylistId == playlistid);


            for (int i = 0; i < content.Count; i++)
            {
                var pc = new PlaylistContent();
                pc.Sequence = content[i].MetaID;
                playlist.PlaylistContents.Add(pc);
            }
            for (int i = 0; i < deleted.Count; i++)
            {
                long delid = deleted[i];
                ar remove = playlist.PlaylistContents.FirstOrDefault(x => x.PlaylistContentId.Equals(delid));
                playlist.PlaylistContents.Remove(remove);


            }
            db.SaveChanges();
            return JSON(playlist);

        }

値は正常に追加されますが、それらから値を削除するときに、次のようにエラーが表示されます::

 The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

このエラーを解決するにはどうすればよいですか。ビジネス ロジックに間違いはありますか。

4

3 に答える 3

2

次のコードは、コレクションからオブジェクトを削除します。

playlist.PlaylistContents.Remove(remove);

ただし、SaveChanges を呼び出すと、FK 列が null 許容ではないため失敗します。なんで?EF は行を削除しているのではなく、id 値をゼロに設定しているためです。行を削除する必要があります。そのためには、次のようにします。

db.PlaylistContents.Remove(remove); // this line removes the row from the database
playlist.PlaylistContents.Remove(remove); // this line removes the object form the collection
db.SaveChanges();
于 2014-05-28T21:51:46.183 に答える