c# - 无法更改关系,因为一个或多个外键属性不可为空

标签 c# asp.net-mvc entity-framework

我正在尝试添加一些值以及尝试从我的数据库中删除选定的值。

我使用的代码如下:

[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.

我该怎么做才能解决这个错误。业务逻辑中是否存在任何类型的错误。

最佳答案

以下代码从集合中删除对象:

playlist.PlaylistContents.Remove(remove);

但是,当您调用 SaveChanges 时,它会失败,因为 FK 列不可为空。为什么?因为 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();

关于c# - 无法更改关系,因为一个或多个外键属性不可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16806715/

相关文章:

c# - 如何使用 DataTemplate + 触发器在 View 之间切换

asp.net-mvc - asp.net mvc 4 - razor View 中的 DataAnnotations 验证(正则表达式)

c# - 如何在 ASP.NET MVC 和 jQuery 中根据下拉列表选择添加额外的部分 View ?

c# - 使用 Entity Framework 搜索单个项目并将其作为数据传输对象返回?

c# - 将列表中的子集保存到对象中

c# - TcpListener HTTP 文件上传随机失败

asp.net - .cshtml 文件显示为纯 html

c# - Entity Framework Code First 对象实例化回调

c# - Entity Framework 6 自动编译查询

c# - ASP.NET MVC - 从 View 中的 URL 获取参数值