Adding a new entry that has no foreign keys results in a "The relationship could not be changed [..]" error

88 Views Asked by At

I am running into a weird problem. When I deploy my code, everything works. I can add orders to my system. However, after some orders has been made, I start to get the famous 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.

Now, I have read a lot about that error, but it doesn't help my case. I have a very simple database without any foreign keys:

enter image description here

My code looks like the following:

    public NewOrder Create(NewOrder order)
    {
        var o = new WebshopOrder();
        o.AdvertId = order.AdvertId;
        o.DateCreated = DateTime.Now;
        o.IsActivated = order.OrderState > OrderState.Created;
        o.ProductId = order.Product.Id;
        o.UserId = order.UserId.ToString();

        Db.WebshopOrder.Add(o);
        Db.SaveChanges();

        return new NewOrder() { WebshopOrderId = o.Id};
    }

Which in turn, then fails when I say Db.SaveChanges().

Any idea what on earth could be wrong here?

2

There are 2 best solutions below

0
On BEST ANSWER

I see three possibilities at the moment:

  1. ProductId is being sent to the DB as NULL
  2. OrderId is being sent to the DB as NULL
  3. Timestamp is being sent to the DB as NULL

I think it is complaining about one of those three columns that are the only ones that do NOT allow NULL. I think ProductId has the greatest chance of being the culprit, where your code is being called sometimes with a value there, and others times it is receiving a NULL product.

This may, or may not be the issue, but your code has:

order.Product.Id

Did you want to use this instead?

order.ProductId

That error message would be improved if it were split into two or more errors with each being more specific.

0
On

I can see from your question that you are looking into the Order table for relationships.

Instead you have to look into WebshopOrder table for any relations, because you are saving the WebshopOrder

Db.WebshopOrder.Add(o);
Db.SaveChanges();