I have an entity with a referential constraint of the form: Entity->Others and am attempting to delete the entity in question.
After loading the entity is deleted, then saved back, this works fine.
Entity entity = null;
entity = db.Entities.Where(o => o.Id == loadId).FirstOrDefault();
db.Entities.DeleteObject(entity);
db.SaveChanges();
Adding a single check to the entities of type Other related via the referential constraint causes an exception to be thrown on save
Entity entity = null;
entity = db.Entities.Where(o => o.Id == loadId).FirstOrDefault();
entity.Others.Count();
db.Entities.DeleteObject(entity);
db.SaveChanges();
With the exception being:
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’m not expecting much as I don’t have a complete and minimal code here, but the vaguest suggestion of how simply accessing Others invalidates the Entity for saving back would be hugely appreciated.
Looks like some error in you mapping. Either you are using database first and your database has cascade delete allowed between
EntityandOrderbut your EDMX models doesn’t or your database allows existence ofOrderswithoutEntity(nullable FK) but your classes do not.In the first case select the association in EDMX and modify its properties to support
OnDeletein the right direction. In the latter case make sure that cardinality betweenEntityandOrderis 0..1-N instead of 1-N. If you have FK exposed inOrdermake sure that it is nullable.Without cascade delete or nullable FK your first example should throw error (unless you have turned off constraint validation in the database which you should NEVER do). In such case you must first delete every dependent all dependent entities (
Orders) before you can delete principal (Entity).