I can imagine that this weird exception could occur if you are initializing the Account
navigation property in the License
constructor like so:
public License
{
Account = new Account();
}
The flow when you call...
var entityToDelete = context.Licenses.Find(licenseId);
context.Licenses.Remove(entityToDelete);
...is then probably:
License
entity gets loaded (without navigation propertyAccount
) and attached to the context (stateUnchanged
)- The constructor sets the
Account
navigation property, but it doesn't get attached (stateDetached
) - When you call
Remove
for theLicense
entityDetectChanges
is called internally by EF. It detects thatLicense.Account
is refering to a detached entity and attaches it to the context (in stateAdded
). The state of theLicense
is changed toDeleted
. - When you call
SaveChanges
the change tracker finds two entities: TheLicense
in stateDeleted
and theAccount
in stateAdded
. - Validation runs and finds that the required property
CustomerName
for the entityAccount
that is supposed to be inserted into the database isnull
(because only the default constructor ofAccount
is called). - The validation exception is thrown.
I'm not sure if the details are right but something like that is probably happening.
In any case you should delete the Account = new Account();
from the License
constructor and also check if you initialize other reference navigation properties in entity constructors in your codebase as well. (Initializing empty navigation collections is OK.) This is a common source of notoriously strange problems that are difficult to find and understand.