Reputation: 237
I am trying to add some values as well as trying to remove the selected values from my Database.
I am using code as below:
[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 Values get added Successfully But at the time of deleting the values from them then the Error is shown like this::
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.
what can I do to solve this Error. Is there any kind of Mistakes in the Business logic.
Upvotes: 3
Views: 2703
Reputation: 13767
The following code removes the object from the collection:
playlist.PlaylistContents.Remove(remove);
But, when you call SaveChanges, it fails because the FK column is not nullable. Why? because EF is not deleting the row but setting the id value to zero. You need to delete the row and in order to do that you can do this:
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();
Upvotes: 2
Reputation: 8506
I solved this doing similar to this:
DataModel.PlayListContent.Remove(remove)
Upvotes: 1
Reputation: 14864
There is a relation between two objects which is not Optional
, you can add the Optional
to your mapping to enable setting the null value for foreign keys.
This question EF 4.1: Difference between .WithMany() and .WithOptional() ? will help.
Upvotes: 0