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:
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?
I see three possibilities at the moment:
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:
Did you want to use this instead?
That error message would be improved if it were split into two or more errors with each being more specific.