由于一个或多个外键属性不可为空,因此无法更改关系

时间:2013-05-29 06:12:47

标签: 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.

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

3 个答案:

答案 0 :(得分:2)

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

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();

答案 1 :(得分:1)

我解决了这个问题:

DataModel.PlayListContent.Remove(remove)

答案 2 :(得分:0)

两个对象之间存在一个非Optional的关系,您可以将Optional添加到映射中,以便为外键设置空值。

这个问题EF 4.1: Difference between .WithMany() and .WithOptional() ?会有所帮助。