I try to update the model, but I get the error message “Operation failed: the relation cannot be changed because one or more properties of the foreign key are not NULL. When the relation changes, the corresponding property of the foreign key is set to zero. If the foreign key doesn’t support null values, a new relationship needs to be defined, another nonzero value must be assigned to the foreign key property, or an unrelated object must be deleted. "
From what I understand from Relationships cannot be changed, since one or more properties of the foreign key cannot be nullified , the problem may be due to the way the Entity Framework handles my virtual ICollection
However, I'm not sure how to implement the solution when using the forest repository template. Do I need to edit the Save () class - method ParentObjectRepository-class?
Actually, I really think there must be some way to get EF to understand this. I don’t see what the EF team thought: "Probably no one uses a collection of objects with foreign key constraints, doesn’t support this."
Update Code Added
[HttpPost] public ActionResult Edit(int id, FormCollection formCollection) { var eventRepository = new MagnetEventRepository(); var original = eventRepository.Find(id); UpdateModel(original); eventRepository.Save(); return RedirectToAction("Details", "Home", new { slug = original.Slug }); } public void Save() { context.SaveChanges(); }
More code:
public class MagnetEvent { public virtual int Id { get; set; } [Required] public virtual string Name { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}")] [DataType(DataType.DateTime)] public virtual DateTime? StartDate { get; set; } public virtual string Description { get; set; } [StringLength(100)] public virtual string Slug { get; set; } public virtual int MaximumCapacity { get; set; } [DataType(DataType.Currency)] public virtual int TicketPrice { get; set; } public virtual int LocationId { get; set; } public virtual Location Location { get; set; } public virtual Collection<Ticket> Tickets { get; set; } public virtual Collection<AttendeeInformationField> CaptureAttendeeInformationFields { get; set; } public virtual int CustomerId { get; set; } [Required] public virtual CUSTOMER Customer { get; set; } }
The Save () method is the MagnetEventRepository method, which is taken from the above class.
Another update I successfully removed the error by changing the MagnetEventId in AttendeeInformationField to null. When examining the database, I can see for sure what is wrong.
Let's say I have one AttendeeInformationField with the value "E-mail". When I edit MagnetEvent, the AttendeeInformationField updates MagnetEventId to zero, and then adds a new message with the correct MagnetEventId and Value.
I would really like the posts in the AttendeeInformationField to be updated instead.