I'm trying to remove a relationship with the following code:
var serverVideo = InternalGetVideo(db, videoId);
// get owning user
var owner = InternalGetUser(db, serverVideo.UserId);
// Add/remove video to user's upvotedVideos
if (owner.UpvotedVideos.Contains(serverVideo))
{
serverVideo.UpVotes--;
SaveChanges(db); // Works
owner.UpVotes--;
SaveChanges(db); // Works
owner.UpvotedVideos.Remove(serverVideo);
SaveChanges(db); // Breaks
}
SaveChanges(db);
But I always get this error:
The operation failed: 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.
I'm not trying to delete the video, I'm just trying to remove it from the user's UpvotedVideos property (it's there):
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Username { get; set; }
public int UpVotes { get; set; }
public virtual List<Video> UpvotedVideos { get; set; }
public string Email { get; set; }
}
Videos does not contain a reference to UserProfiles - it's a one-to-many relationship. Any idea what I'm doing wrong?
Videos class:
[DataContract]
public class Video
{
[Key]
[DataMember(IsRequired = false)]
public int VideoId { get; set; }
[DataMember(IsRequired = false)]
public int UserId { get; set; } // user that created the video, unrelated
[Required]
[DataMember]
public virtual IList<Tag> Tags { get; set; }
}