Igor Ralic
Igor Ralic

Reputation: 15006

Entity Framework foreign key InvalidOperationException

Is there a way to somehow output more details/information when InvalidOperationException like this one happens during SaveChanges() call?

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.

I am not removing anything from the DB so questions similar to this one didn't help me. The message is quite self-explanatory, true, but I just can't see the mistake in code and it would be helpful if the exception gave more information about which property and which foreign key is in question.

EDIT - I have checked the InnerException and it's empty.

Upvotes: 3

Views: 1173

Answers (1)

Lucas L Roselli
Lucas L Roselli

Reputation: 2830

For example, if you have the next structure:

  public class Client
  {
     public int ClientID { get; set; }
     public string Name { get; set; }

     public int ClientTypeID { get; set; }
     public ClientType ClientType { get; set; }
  }

  public class ClientType
  {
     public int ClientTypeID { get; set; }
     public string Description { get; set; }
  }

If you are changing the "Name" propertie for example, your property "ClientType" must be null, otherwise it will try to create,update or delete your client type.

So just set the ClientType to null, before SaveChanges();

If you post more of your code, we can be sure what exactlly it's happening, but this was my guess

Upvotes: 2

Related Questions