locked
Cascade Deleting in POCO mode RRS feed

  • Question

  • Hello,

    I'am looking for help about the cascade deleting with entity framework 4.0 with POCO.

    I have a little model with 2 entities "Vehicule" and "Tickets". There is a foreign key from Vehicule to Tickets (on IdVehicule).

    [Vehicule] 1 ----------------------------- * [Tickets]

    I'd like to delete a Vehicule and every tickets attached to it. So, I have a delete method like this : 

            public void DeleteVehicule(Vehicule del)
            {
                using (Session oSession = new Session())
                {
                    try
                    {
                        oSession.Context().AttachTo("Vehicule", del);
                        ObjectStateEntry entry = oSession.Context().ObjectStateManager.GetObjectStateEntry(del);
                        entry.ChangeState(EntityState.Deleted);
                        oSession.Context().SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException("Error during deleting the IdVehicule : " + del.IdVehicule);
                    }
                }
            }
    


    When I call it, it crashes without any other detail than this :

    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.

    So, I change the property of the IdVehicule FK in Ticket table to "Allows null", I updated my model and I still have this error message.

     

    Please Help !

    Monday, October 3, 2011 3:50 PM

Answers

  • Hi cabrinha,

    Welcome!

    Which type are you using Model First, Database First?

    If you are using Model First, you should set the property for the 1ToM relationship(End OnDelete to Cascade), the generated T-SQL will create the Cascade in database.

    If you are using Database First, you should manually set Cascade in database and change the relateship to mapping database.

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Alan_chen Tuesday, October 18, 2011 2:05 AM
    Wednesday, October 5, 2011 2:20 AM