none
Deleting Items with EF6 MVC 5 The operation failed error RRS feed

  • Question

  • I am using UnitofWork and EF 6 with MVC and want to delete items. When I create an item the first time and want to delete it  right away, I get the error below but when I close my browser and re-open the same page, I can delete the same item with no error. Below is the error I am getting

    Message "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."
    - TargetSite {Void PrepareToSaveChanges(System.Data.Entity.Core.Objects.SaveOptions)
    } System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}

    My delete code

     [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Delete)]
            public async Task<ActionResult> Delete(int contId)
            {
                try
                {
    				var cont = await _myRepository.FindAsync(contId);
    				
                    if (cont == null)
                    {
    					return RedirectToAction("Index", "Documents").WithError("Unable to find the Document.  Maybe it was deleted?");
                    }
    			         
    				cont.ObjectState = ObjectState.Deleted;
    				_myRepository.Delete(cont);
    				await _uow.SaveChangesAsync();
                    return RedirectToAction("Index", "Documents").WithSuccess("Successfully Delete");
                    
                }
                catch (Exception ex)
                {
                    ControllerProvider.ProcessDataAccessLayerException(ex);
                    ControllerUnHandledExp.LogError(ex);
                    
                    throw;
                }
            }


    Ebenezer

    Monday, December 21, 2015 1:39 AM

Answers

  • Hello denkyira,

    Since your program is asynchronous, I guess when you delete, the database has not been the piece of data, but you re-open the page, the piece of data has been inserted into the database. You could remove the asynchronous, see if that can solve this problem?

    Best regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by denkyira Tuesday, December 22, 2015 4:17 PM
    Tuesday, December 22, 2015 8:46 AM
    Moderator

All replies

  • it seems to me that you would try to get the object first, before trying to delete it. If you cannot get it by its ID, it's not there to delete.
    Monday, December 21, 2015 3:31 AM
  • The ID is never null but I will try and get the item like you said and update you tomorrow morning

    Ebenezer


    • Edited by denkyira Monday, December 21, 2015 3:38 AM
    Monday, December 21, 2015 3:37 AM
  • I have changed the code to get the object before deleting but still getting the same error. Below is my new code

       public async Task<ActionResult> Delete(int contId)
            {
                try
                {
    	            var cont = from c in _myRepository.Queryable()
    		            from cr in c.Roles
    		            from ct in c.Targets
    		            where c.Id == contId
    		            select c;
    
    	            foreach (var item in cont)
    	            {
    		            item.ObjectState = ObjectState.Deleted;
    				
    			   _myRepository.Delete(item);
    					
    	            }
     
    		await _uow.SaveChangesAsync();
                    return RedirectToAction("Index", "Documents").WithSuccess("Successfully Delete");
                    
                }
                catch (Exception ex)
                {
                    ControllerProvider.ProcessDataAccessLayerException(ex);
                    ControllerUnHandledExp.LogError(ex);
                    // TODO Russ to create an error page
                    throw;
                }
            }

    Error

    + InnerException {"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."} System.Exception {System.InvalidOperationException}


    Ebenezer

    Monday, December 21, 2015 1:38 PM
  • var cont =( from c in _myRepository.Queryable() from cr in c.Roles
               
    from ct in c.Targets
               
    where c.Id == contId
               
    select c).SingleOrDefault();
    if (cont != null)

    {

      //you got  an object back

    }

    Monday, December 21, 2015 4:13 PM
  • Hi

    Yes I get Data back. Like I said I get data back but can only delete when I close the browser and re-open the page again. Then delete works fine. I am attaching two screenshots


    Ebenezer


    • Edited by denkyira Monday, December 21, 2015 4:46 PM
    Monday, December 21, 2015 4:44 PM
  • Hi 

    I have checked the code again. This  cont is null from this code

    var cont =( from c in _myRepository.Queryable() from cr in c.Roles
                from ct in c.Targets
                where c.Id == contId
                select c).SingleOrDefault();
    if (cont != null)

    {

      //you got  an object back

    }


    Ebenezer

    Monday, December 21, 2015 5:03 PM
  • Hi 

    I have checked the code again. This  cont is null from this code

    var cont =( from c in _myRepository.Queryable() from cr in c.Roles
                from ct in c.Targets
                where c.Id == contId
                select c).SingleOrDefault();
    if (cont != null)

    {

      //you got  an object back

    }


    Ebenezer

    Null means no object was returned the object was not found by its ID, and therefor you can't send in a null object that is not there to be deleted, because otherwise, the code is going to blowup if you do send in a null object.   
    Monday, December 21, 2015 5:42 PM
  • I think I have narrow my issue down. I am Implementing unitofwork with AutoMapper. There are two tables on first delete shows value and hence unable to delete. When I close the browser and re-open the page, those tables becomes empty and delete works. I need to figure out why their data are unable to reload

    Ebenezer

    Monday, December 21, 2015 6:05 PM
  • I think I have narrow my issue down. I am Implementing unitofwork with AutoMapper. There are two tables on first delete shows value and hence unable to delete. When I close the browser and re-open the page, those tables becomes empty and delete works. I need to figure out why their data are unable to reload

    Ebenezer

    I never liked Repository or UoW and avoid them  I like DAO. I am also no fan of using EF at a MVC or WebAPI controller either (trouble), as I don't view that as a true separation of concerns a (DAL).

    Monday, December 21, 2015 6:28 PM
  • Hello denkyira,

    Since your program is asynchronous, I guess when you delete, the database has not been the piece of data, but you re-open the page, the piece of data has been inserted into the database. You could remove the asynchronous, see if that can solve this problem?

    Best regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by denkyira Tuesday, December 22, 2015 4:17 PM
    Tuesday, December 22, 2015 8:46 AM
    Moderator
  • Hi Fred

    My issue is not the asynchronous. I have figured out the issue now I need the solution. I am using structureMap for IoC. For some reasons the transaction per request doesn't complete for a session until I close the application so although the data inserts into the database correctly and I can see it before delete, the transaction will be active.

    I am looking for help in setting the structuremap session correctly for unitofwork


    Ebenezer

    Tuesday, December 22, 2015 12:41 PM
  • Hi Fred

    Sorry you was 100% correct. I took out the asynchronous and it works perfectly correctly. Thanks

    Eb


    Ebenezer

    Tuesday, December 22, 2015 4:16 PM