Foreign key constraint, EF with collection of chil

2019-03-06 08:20发布

问题:

I'm trying to update a model, but get the 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."

From what I understand from The relationship could not be changed because one or more of the foreign-key properties is non-nullable the problem might be with how Entity Framework handles my virtual ICollection

However I'm not really sure how to implement the solution when using scaffolded repository pattern. Do I have to edit the Save()-method ParentObjectRepository-class?

Actually I really think that there must be some way to make EF understand this. I can't see how the EF-team was thinking "Probably noone is using a collection of objects with a foreign key constraint, lets not support that".

Update Added code

[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 from MagnetEventRepository, which is scaffolded from the above class.

Another update I successfully removed the error by changing MagnetEventId in AttendeeInformationField to nullable int. When examining the database I can see exactly what's wrong.

Let's say I have a single AttendeeInformationField with the value "E-mail". When I edit my MagnetEvent, the AttendeeInformationField updates the MagnetEventId to null and then adds a new post with the correct MagnetEventId and Value.

I'd very much prefer if the posts in AttendeeInformationField were updated instead.

回答1:

can you add the code for your event object. The one you call original.

It might be so that the UpdateModel change some info on the associated objects and that's not good if so. Not sure about this though I can't see all the code.

I prefer to not uder UptadeModel and instead use a inputmodel or your MVC model as the inparameter and manually map the chages to the loaded original object.

Antoher problem is that I can't see if eventRepository.Save();

really do an SaveShages? does it? I can se some context code in another method Save?



回答2:

As the exception say it seams like your associated collections or other associated objects cant find a valid ID value.

Are you Eager-loading the associated objects? like Customer?



回答3:

One thing of note is that you shouldn't have the [Required] on Customer as its inferred from the fact that your FK isn't nullable. Required should only be used on a navigation property if you do not have the FK in the model.

To try to diagnose the issue, can you load the object and look at it in a debugger, you should expect that both locationId and CustomerId have non-zero values.



回答4:

I found a solution to my problem. It seems to be a bug (?) in ASP.NET MVC when it comes to UpdateModel and a model containing an ICollection.

The solution is to override the default behaviour, as described in this blog post: http://www.codetuning.net/blog/post/Binding-Model-Graphs-with-ASPNETMVC.aspx

Update I found a solution! The above only worked when updating existing items in the collection. To solve this, I have to manually check and add new AttendeeInformationFields. Like this:

[HttpPost]
public ActionResult Edit(int id, MagnetEvent magnetEvent)
{
    var eventRepository = new MagnetEventRepository();
    var original = eventRepository.Find(id);
    UpdateModel(original);
    foreach (var attendeeInformationField in magnetEvent.CaptureAttendeeInformationFields)
    {
        var attendeeInformationFieldId = attendeeInformationField.Id;
        if (original.CaptureAttendeeInformationFields.AsQueryable().Where(ai => ai.Id == attendeeInformationFieldId).Count() == 0)
        {
            original.CaptureAttendeeInformationFields.Add(attendeeInformationField);
        }
    }
    eventRepository.Save();
}

Together with the modified DefaultModelBinder, this actually works with both editing and adding. For now I haven't tried deleting.

Still, I hope there is a simpler way to do this. Seems like a lot of coding to do a very basic task.