0

I have an Itinerary which may contains 0, 1 or more TransportInfos.

public class Itinerary
{
    [Key]
    public int Id { get; set; }
    ...
    public virtual List<TransportInfo> TransportInfos { get; set; }
}

public class TransportInfo
{
    [Key]
    public int Id { get; set; }
    ...
    public virtual Itinerary Itinerary { get; set; }
}

Then I have the following function to delete a bunch of itineraries and related TransportInfos.

    public void DeleteItineraries(IEnumerable<int> ids)
    {
        var itinerariesToDelete = Context.Itineraries.Where(it => ids.Contains(it.Id)).Include(b => b.TransportInfos).ToList();

        itinerariesToDelete.ForEach(it =>
        {
            it.TransportInfos.ForEach(ti => Context.TransportInfos.Remove(ti));
            Context.Itineraries.Remove(it);
        });
        Context.SaveChanges();
    }
  • If I have only 1 TransportInfo inside my Itinerary then the delete succeed.

  • If I have more than 1 TransportInfo inside my Itinerary then I got the error below:

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.

Any idea?

4

1 回答 1

0

尝试进行以下更改:

  • 将 ItineraryID 添加到 TransportInfo
  • 将列表更改为 ICollection
于 2013-11-13T15:55:04.890 回答