首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法更改关系,因为一个或多个外键属性不可为空

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

Stack Overflow用户
提问于 2013-05-29 14:12:47
回答 3查看 2.7K关注 0票数 3

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

我使用的代码如下:

代码语言:javascript
复制
[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);

        }

值被成功添加,但在删除其中的值时,错误显示如下::

代码语言:javascript
复制
 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.

我能做些什么来解决这个错误。

EN

回答 3

Stack Overflow用户

发布于 2014-05-29 05:51:46

下面的代码从集合中移除该对象:

代码语言:javascript
复制
playlist.PlaylistContents.Remove(remove);

但是,当您调用SaveChanges时,它会失败,因为FK列不可为空。为什么?因为EF不会删除该行,而是将id值设置为零。您需要删除该行,为此,您可以执行以下操作:

代码语言:javascript
复制
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();
票数 2
EN

Stack Overflow用户

发布于 2013-11-21 21:59:45

我用类似的方法解决了这个问题:

代码语言:javascript
复制
DataModel.PlayListContent.Remove(remove)
票数 1
EN

Stack Overflow用户

发布于 2013-05-29 14:15:54

两个不是Optional的对象之间存在关系,您可以将Optional添加到映射中以允许设置外键的null值。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16806715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档