Delete Record LINQ to ENTITY

0

I try to delete a record in this way:

 var cSelect = from x in contexto.BloqueoExcursion
                      where x.BLE_BloqueoID == BloqueoID
                      select x;




        foreach (var item in cSelect)
        {
            var eSelect = new BloqueoExcursion { BloqueoExcursionId = item.BloqueoExcursionId, BLE_BloqueoID = item.BLE_BloqueoID, BLE_ExcursionId = item.BLE_ExcursionId, BLE_PrecioExc = item.BLE_PrecioExc };
           contexto.Entry(eSelect).State = System.Data.Entity.EntityState.Deleted;

        }

Then I tried like this:

contexto.ChangeObjectState(eSelect, System.Data.EntityState.Deleted);

And also like this:

contexto.BloqueoExcursion.Remove(eSelect);

The first two options give me the following error:

  

System.InvalidOperationException: 'Error when attaching an entity of type' Manager_Mayorist.Models.BlockingExcursion 'because another entity of the same type already has the same primary key value. This can occur when the 'Attach' method is used or when the state of an entity is set to 'Unchanged' or 'Modified' if some entities in the graph have conflicting key values. It may be because some entities are new and have not yet received the key values generated by the database. In this case, use the 'Add' method or the 'Added' entity state to track the graph and then set the status of non-new entities such as' Unchanged 'or' Modified ', as appropriate.'

If I use this instruction:

contexto.BloqueoExcursion.Remove(eSelect);

This tells me:

  

System.InvalidOperationException: 'The object can not be deleted because it was found in the ObjectStateManager.'

I RECALL THAT:

  • I do not use related entities.
  • I do not have relations in the tables.
  • The Linq if it brings data (2 records).
  • Thanks for the help.

        
    asked by Eduardo SC 11.08.2017 в 01:55
    source

    1 answer

    1

    Try the following:

    var cSelect = from x in contexto.BloqueoExcursion
                      where x.BLE_BloqueoID == BloqueoID
                      select x;
    
    contexto.BloqueoExcursion.RemoveRange(cSelect);
    contexto.SaveChanges();
    

    Or better yet:

    contexto.BloqueoExcursion.RemoveRange(contexto.BloqueoExcursion.Where(x => x.BLE_BloqueoID == BloqueoID));
    contexto.SaveChanges();
    

    In the case of contexto.BloqueoExcursion.Remove(eSelect); the error is because you try to delete an entity that is not in DbSet because you just instantiated it. You must refer to the same entities that you took out of context.

        
    answered by 11.08.2017 / 02:02
    source